[LeetCode] 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 are 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

统计「优美子数组」。

题意是给你一个整数数组 nums 和一个整数 k。如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。请返回这个数组中「优美子数组」的数目。

思路

子数组的题一般可以试图往 sliding window 或者前缀和 prefix sum 上靠,本题我两种解法都给出。

思路一 - 前缀和

首先前缀和的思路是遍历 input 里面的每个数字,把他们的前缀和 sum出现次数加到 hashmap 里面,但是这一题跟 560 题的区别在于,560 是在找一个特别的子数组的和 k,而本题是在找有多少个包含 k 个奇数的子数组,他并不在意子数组的和或者长度是多少。所以思路是遇到奇数的时候可以把这个数字改成 1,遇到偶数的时候可以把这个数字改成 0。当累加 prefix sum 的时候,因为从 0 到当前位置的前缀和为 sum,所以如果找到一个前缀和 sum - k,则说明存在这样一个优美子数组。

复杂度

时间O(n)
空间O(n)

代码

Java实现

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int res = 0;
        int n = nums.length;
        int sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int i = 0; i < n; i++) {
            sum += nums[i] % 2 == 1 ? 1 : 0;
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            res += map.getOrDefault(sum - k, 0);
        }
        return res;
    }
}

思路二 - 滑动窗口

既然题目说找的是恰好k 个奇数数字的子数组,那么我们可以沿用 992 题的思路。即最多 k 个奇数数字的子数组 - 最多 k - 1 个奇数数字的子数组 = 正好 k 个奇数的子数组。

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        return helper(nums, k) - helper(nums, k - 1);
    }

    private int helper(int[] nums, int k) {
        int start = 0;
        int end = 0;
        int res = 0;
        while (end < nums.length) {
            if (nums[end] % 2 == 1) {
                k--;
            }
            end++;
            while (k < 0) {
                if (nums[start] % 2 == 1) {
                    k++;
                }
                start++;
            }
            res += end - start + 1;
        }
        return res;
    }
}
posted @ 2020-04-21 07:58  CNoodle  阅读(921)  评论(0)    收藏  举报