Given an array of integers nums
and an integer k
. A continuous subarray is called nice if there are k
odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1 Output: 0 Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
题目链接:https://leetcode.com/problems/count-number-of-nice-subarrays/
题目大意:求包含k个奇数的子数组个数
题目分析:用一个数组pos记录奇数数字的下标,对每个奇数分别累计其左边和右边有多少个偶数记为数组l0和r0,接着枚举计算即可,对第i个奇数和第i+k-1个奇数,他们能构成的长度为k的子数组为(1+l0[pos[i]]) * (1 + r0[pos[i+k-1]])
12ms,时间击败81.3%
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int n = nums.length, sum = 0;
int[] pos = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (nums[i - 1] % 2 == 1) {
pos[++sum] = i;
}
}
int[] r0 = new int[n + 1];
int cntr0 = 0;
for (int i = n; i >= 1; i--) {
if (nums[i - 1] % 2 == 0) {
cntr0++;
} else {
r0[i] = cntr0;
cntr0 = 0;
}
}
int[] l0 = new int[n + 1];
int cntl0 = 0;
for (int i = 1; i <= n; i++) {
if (nums[i - 1] % 2 == 0) {
cntl0++;
} else {
l0[i] = cntl0;
cntl0 = 0;
}
}
int ans = 0;
for (int i = 1; i + k - 1 <= sum; i++) {
if (pos[i] != 0 && i + k - 1 <= sum && pos[i + k - 1] != 0) {
ans += (1 + l0[pos[i]]) * (1 + r0[pos[i + k - 1]]);
}
}
return ans;
}
}