# 1248. Count Number of Nice Subarrays

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`

``````class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
return atMost(nums, k) - atMost(nums, k - 1);
}
int atMost(vector<int>& nums, int k) {
int res = 0, left = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
k -= nums[i] % 2;
while (k < 0) {
k += nums[left++] % 2;
}
res += i - left + 1;
}
return res;
}
};
``````

``````class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int res = 0, left = 0, cnt = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
if (nums[i] % 2 == 1) {
--k;
cnt = 0;
}
while (k == 0) {
k += nums[left++] & 1;
++cnt;
}
res += cnt;
}
return res;
}
};
``````

``````class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int res = 0, cur = 0, n = nums.size();
unordered_map<int, int> m{{0, 1}};
for (int i = 0; i < n; ++i) {
cur += nums[i] & 1;
res += m[cur - k];
++m[cur];
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1248

Number of Substrings Containing All Three Characters

Replace the Substring for Balanced String

Max Consecutive Ones III

Binary Subarrays With Sum

Subarrays with K Different Integers

Shortest Subarray with Sum at Least K

Minimum Size Subarray Sum

Subarray Sum Equals K

https://leetcode.com/problems/count-number-of-nice-subarrays/

https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419483/Subarray-Sum-Equals-K

https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419378/JavaC%2B%2BPython-Sliding-Window-O(1)-Space

LeetCode All in One 题目讲解汇总(持续更新中…)

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation