1. Title
Gives you an array of integers nums and an integer k.
If a continuous subarray exactly k in odd numbers, we believe that this is a sub-array "Yumiko array."
Please return the number of "beautiful subarrays" in this array.
示例 1:
输入:nums = [1,1,2,1,1], k = 3
输出:2
解释:包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 。
示例 2:
输入:nums = [2,4,6], k = 1
输出:0
解释:数列中不包含任何奇数,所以不存在优美子数组。
示例 3:
输入:nums = [2,2,2,1,2,2,1,2,2,2], k = 2
输出:16
提示:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/count-number-of-nice-subarrays The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
2. Problem solving
2.1 Record odd pos
- Find the even number of k odd numbers, multiply it is the number of solutions
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int i, cnt = 0, n = nums.size(), count = 0;
vector<int> oddPos(n+2);
for(i = 0; i < n; ++i)
{
if(nums[i] & 1)//奇数
oddPos[++cnt] = i;
}
oddPos[0] = -1, oddPos[++cnt] = n;//边界,假设两边有0个偶数
for(i = 1; i+k <= cnt; ++i)
count += (oddPos[i]-oddPos[i-1])*(oddPos[i+k]-oddPos[i+k-1]);
return count;
}
};
372 ms 66.1 MB
2.2 Prefix and
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int i, oddcnt = 0, n = nums.size(), count = 0;
vector<int> preOddCnt(n+1,0);
preOddCnt[0] = 1;//边界
for(i = 0; i < n; ++i)
{
oddcnt += (nums[i]&1);//奇数多少个了
preOddCnt[oddcnt] += 1;//这么多个奇数的数组 +1 个
if(oddcnt >= k)//奇数够个数了
count += preOddCnt[oddcnt-k];
//以i结束的长度为k个奇数的数组个数 preOddCnt[oddcnt-k]
}
return count;
}
};
368 ms 65.8 MB