URL : https://leetcode.com/problems/subarrays-with-k-different-integers/
思路:
該題其實代碼量不多,但是思路不好想,我是看了discuss才恍然大悟。下面給出代碼。
數組中最多出現K個不同的數字的組合數爲N, 數組中最多出現K-1個不同的數字的組合數爲M,則我們想要的結果是出現K個不同的組合數N-M.
最多出現K個不同的數字的組合數的計算方法則相對簡單啦,使用滑動窗口,在窗口內的不同數字不超過K就行了。
public int subarraysWithKDistinct(int[] A, int K) {
return AtMost(A,K) - AtMost(A, K-1);
}
public int AtMost(int[]A, int k) {
int[] map = new int[20001];
int pre=0;int res=0;
int count = 0;
for (int i=0;i<A.length;i++) {
map[A[i]]++;
if (map[A[i]] == 1) {
count++;
}
if (count <= k){
res += i- pre +1;
}
while(count > k) {
int tmp = map[A[pre]];
if (tmp == 1) {
res += i - pre;
count--;
}
map[A[pre++]]--;
}
}
return res;
}