返回介绍

solution / 1200-1299 / 1248.Count Number of Nice Subarrays / README_EN

发布于 2024-06-17 01:03:21 字数 3819 浏览 0 评论 0 收藏 0

1248. Count Number of Nice Subarrays

中文文档

Description

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

Solutions

Solution 1: Prefix Sum + Array or Hash Table

The problem asks for the number of subarrays that contain exactly $k$ odd numbers. We can calculate the number of odd numbers $t$ in each prefix array and record it in an array or hash table $cnt$. For each prefix array, we only need to find the number of prefix arrays with $t-k$ odd numbers, which is the number of subarrays ending with the current prefix array.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.

class Solution:
  def numberOfSubarrays(self, nums: List[int], k: int) -> int:
    cnt = Counter({0: 1})
    ans = t = 0
    for v in nums:
      t += v & 1
      ans += cnt[t - k]
      cnt[t] += 1
    return ans
class Solution {
  public int numberOfSubarrays(int[] nums, int k) {
    int n = nums.length;
    int[] cnt = new int[n + 1];
    cnt[0] = 1;
    int ans = 0, t = 0;
    for (int v : nums) {
      t += v & 1;
      if (t - k >= 0) {
        ans += cnt[t - k];
      }
      cnt[t]++;
    }
    return ans;
  }
}
class Solution {
public:
  int numberOfSubarrays(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> cnt(n + 1);
    cnt[0] = 1;
    int ans = 0, t = 0;
    for (int& v : nums) {
      t += v & 1;
      if (t - k >= 0) {
        ans += cnt[t - k];
      }
      cnt[t]++;
    }
    return ans;
  }
};
func numberOfSubarrays(nums []int, k int) (ans int) {
  n := len(nums)
  cnt := make([]int, n+1)
  cnt[0] = 1
  t := 0
  for _, v := range nums {
    t += v & 1
    if t >= k {
      ans += cnt[t-k]
    }
    cnt[t]++
  }
  return
}
function numberOfSubarrays(nums: number[], k: number): number {
  const n = nums.length;
  const cnt = new Array(n + 1).fill(0);
  cnt[0] = 1;
  let ans = 0;
  let t = 0;
  for (const v of nums) {
    t += v & 1;
    if (t - k >= 0) {
      ans += cnt[t - k];
    }
    cnt[t] += 1;
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文