992. 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: 12, and 3.)

Return the number of good subarrays of A.

Example 1:

Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

  1. 1 <= A.length <= 20000
  2. 1 <= A[i] <= A.length
  3. 1 <= K <= A.length
class Solution {
    public int subarraysWithKDistinct(int[] A, int K) {
        int res = 0, prefix = 0;
        //m[A[j]] is the start of the sliding window, should keep m[A[j]] == 1.
        int[] m = new int[A.length + 1];// given "1 <= A[i] <= A.length", use an array instead of hashset to store frequency.
                
        for (int i = 0, j = 0, cnt = 0; i < A.length; ++i) {
            if (m[A[i]]++ == 0) ++cnt;//if current element never shows up, cnt++
            if (cnt > K) {//If cnt > k, means current prefix won't work anymore, reset prefix = 0 to start a new sequence
              --m[A[j++]]; --cnt; prefix = 0; 
            }
            while (m[A[j]] > 1) {// Always keep m[A[j]] == 1 to fit the logic
              ++prefix; --m[A[j++]]; //Move j forwardly
            }
            if (cnt == K) res += prefix + 1;// Current cnt == k means the window is what we're looking for, we add prefix windows and current window.
        }
        return res;
    } 
}

https://www.programmercoach.com/2019/02/interview-pears-sliding-window.html#more

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13161078.html