-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcount-number-of-nice-subarrays.ts
52 lines (47 loc) · 1.06 KB
/
count-number-of-nice-subarrays.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 参考:https://leetcode-cn.com/problems/count-number-of-nice-subarrays/solution/count-number-of-nice-subarrays-by-ikaruga/
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
export const numberOfSubarrays = function (nums:number[], k:number):number {
const odd = []
odd.push(-1)
let ans = 0
let i = 1
for (let j = 0; j <= nums.length; j++) {
if (j === nums.length || (nums[j] & 1)) {
odd.push(j)
}
if (odd.length - i > k) {
const left = odd[i] - odd[i - 1]
const right = j - odd[odd.length - 2]
ans += left * right
i++
}
}
return ans
}
/**
* 错误解法
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
// export const numberOfSubarrays = function (nums, k) {
// let res = 0
// for (let n = 0, len = nums.length; n < len; n++) {
// let num = 0
// let i = n
// while (num < k && i < len) {
// if (nums[i] % 2 !== 0) {
// num++
// }
// i++
// }
// if (num === k) {
// res++
// }
// }
// return res
// }