Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a7f3cb3

Browse files
🐱(sliding-window): 1248. 统计「优美子数组」
1 parent aaa8cdc commit a7f3cb3

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

‎docs/algorithm/sliding-window/README.md‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,4 +212,34 @@ class Solution:
212212
```
213213

214214
- 时间复杂度:$O(l1 + (l2 - l1))$($l1$ 为字符串 s1 长度,$l2$ 为字符串 s2 长度)
215-
- 空间复杂度:$O(1)$
215+
- 空间复杂度:$O(1)$
216+
217+
## 1248. 统计「优美子数组」
218+
219+
[原题链接](https://leetcode-cn.com/problems/count-number-of-nice-subarrays/)
220+
221+
### 滑动窗口
222+
223+
记录奇数的位置。固定 k 个奇数,子数组的个数 = 第一个奇数左边偶数的个数 * 最后一个奇数右边偶数的个数。
224+
225+
```python
226+
class Solution:
227+
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
228+
ans = 0
229+
# 开始位置
230+
odd = [-1]
231+
# 记录奇数下标
232+
for i in range(len(nums)):
233+
if nums[i] % 2 == 1:
234+
odd.append(i)
235+
# 添加结束位置
236+
odd.append(len(nums))
237+
238+
# 遍历奇数数组
239+
for j in range(1, len(odd) - k):
240+
# 从第 i 个到 i + k - 1
241+
# 第 i 个奇数前面的偶数个数 * 第 i + k - 1 后面的偶数个数
242+
ans += (odd[j] - odd[j - 1]) * (odd[j + k] - odd[j + k - 1])
243+
244+
return ans
245+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /