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: 1
, 2
, 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 <= A.length <= 20000
1 <= A[i] <= A.length
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
class Solution { public int subarraysWithKDistinct(int[] a, int k) { int res = 0; int le = a.length; int[] hash = new int[le + 1]; int l = 0, count = 0, prefix = 0; for(int r = 0; r < le; r++) { hash[a[r]]++; if(hash[a[r]] == 1) count++; while(hash[a[l]] > 1 || count > k) { if(hash[a[l]] > 1) { prefix++; } else { prefix = 0; count--; } hash[a[l]]--; l++; } if(count == k) res+=prefix+1; } return res; } }
模板,模板,模板,window:count <= k &&hash[a[l]] <= 1,否则挪动窗口