Count Number of Nice Subarrays

Given an array of integers nums and an integer k. A 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

思路:sliding window讓我們學會了如何求At Most K的區間,那麼Exactly K times = at most K times - at most K - 1 times

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        return getAtMostK(nums, k) - getAtMostK(nums, k - 1);
    }
    
    private int getAtMostK(int[] nums, int k) {
        // two pointers scan;
        int j = 0;
        int oddcount = 0;
        int res = 0;
        for(int i = 0; i < nums.length; i++) {
            // move j;
            while(j < nums.length && oddcount <= k) {
                if(nums[j] % 2 == 1) {
                    if(oddcount == k) {
                        break;
                    }
                    oddcount++;
                }
                j++;
            }
            
            //update result
            res += j - i;
            
            //move i;
            if(nums[i] % 2 == 1) {
                oddcount--;
            }
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章