题目链接:https://leetcode-cn.com/problems/subarrays-with-k-different-integers/
滑动窗口,从左向右遍历
(1)读取一个元素,维护count数组记录出现的次数,如果是第一次出现,count++
(2)如果当前count > K,则左指针右移,直到 count = K
(3)在当前 count == K的前提下,用 t 存放左指针指向位置,继续右移,直到 count < K,否则 res++(记录满足条件的子数组个数)
(4)恢复左指针到 l ,将 l 到当前 t 中间的数组元素数据恢复
(5)重复(1)直到右指针达到数组末尾
代码如下:
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
int len = A.size();
int l = 0, r = 0;
vector<int> cnt(len + 1, 0);
int res = 0, count = 0;
while(r < len) {
if(!cnt[A[r]]) {
count++;
}
cnt[A[r]]++;
while(count > K) {
cnt[A[l]]--;
if(!cnt[A[l]]) {
count--;
}
l++;
}
int t = l;
while(count == K) {
res++;
cnt[A[t]]--;
if(!cnt[A[t]]) {
count--;
}
t++;
}
for(int i = l; i < t; i++) {
if(!cnt[A[i]]) {
count++;
}
cnt[A[i]]++;
}
r++;
}
return res;
}
};