题目
https://leetcode-cn.com/problems/subarrays-with-k-different-integers/
滑动窗口
此题的问法和很多滑动窗口的题目问法类似但还是有些不同,题目中问的是恰好有K个不同整数的区间数量,而一般滑动窗口问的问题是最多。。。。可以将问题转化为最多有K个整数的区间数量,这样的区间数量就是right - left,那么恰好有K个不同整数的区间数量就等于最多有K个整数的区间数量减去最多有K-1个整数的区间数量。
class Solution {
public int subarraysWithKDistinct(int[] A, int K) {
return atMostKDistinct(A, K) - atMostKDistinct(A, K - 1);
}
int atMostKDistinct(int[] A, int K) {
int n = A.length;
int left = 0;
int right = 0;
int[] freq = new int[n + 1];
int counter = 0, res = 0;
while (right < n) {
if (freq[A[right]] == 0) {
counter++;
}
freq[A[right]]++;
right++;
while (counter > K) {
freq[A[left]]--;
if (freq[A[left]] == 0) {
counter--;
}
left++;
}
res += right - left;
}
return res;
}
}