Leetcode 992. Subarrays with K Different Integers

Link: https://leetcode.com/problems/subarrays-with-k-different-integers/

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.

(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)

Return the number of good subarrays of A.

 

It's a sliding window. 

Break down the question to at mostK arrays minus at most K-1 arrays which gives us the exactly K numbers in this array. 

How to find at most K unqiue numbers in this array?

 

1. Build a map

2. Define a window

3. Count the number of valid arrays.

  public int findUnqiueK(int[] nums, int k) {
        return atMost(nums, k) - atMost(nums, k - 1);
  }
private int atMost(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); int left = 0; int res = 0; int count = 0; for(int right = 0; right < nums.length; right++) { if(map.getOrDefault(nums[right], 0) == 0) k--; map.put(nums[right], map.getOrDefault(nums[right], 0) + 1); while(k < 0) { map.put(nums[left], map.get(nums[left]) - 1); if(map.get(nums[left]) == 0) k++; left++; } res += right - left + 1;
       //everytime we are adding a new element in the array and the number of valid arrays due to this elements contributes is the length of the array length. }
return res; }

 

posted @ 2020-09-26 07:26  胖虎刷题  阅读(108)  评论(0)    收藏  举报