文章目录
- 1. 题目
- 2. 解题
- 2.1 记录奇数出现的pos
- 2.2 前缀和
1. 题目
给你一个整数数组 nums 和一个整数 k。
如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。
请返回这个数组中「优美子数组」的数目。
示例 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-number-of-nice-subarrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 类似题目:LeetCode 560. 和为K的子数组(前缀和差分)
2.1 记录奇数出现的pos
- 找到k个奇数左右的偶数个数,相乘就是方案数
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 前缀和
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);//奇数多少个了if(oddcnt >= k)//奇数够个数了count += preOddCnt[oddcnt-k];//以i结束的长度为k个奇数的数组个数 preOddCnt[oddcnt-k]preOddCnt[oddcnt] += 1;//这么多个奇数的数组 +1 个}return count;}
};
368 ms 65.8 MB