File tree Expand file tree Collapse file tree 1 file changed +31
-1
lines changed
docs/algorithm/sliding-window Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -212,4 +212,34 @@ class Solution:
212
212
```
213
213
214
214
- 时间复杂度:$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
+ ```
You can’t perform that action at this time.
0 commit comments