这思路非常好啊,可是想不到啊
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
if(A.size()==0 ||K==0) return 0;
int l=0 ,r=0;
unordered_map<int,int> um;//控制窗口
int res=0;
while(r<A.size())
{
um[A[r]]++;
while(um.size() > K)
{
if(um[A[l]]>1)
um[A[l]]--;
else
um.erase(A[l]);
l++;
}
int temp=l;//临时存left
while(um.size() == K)//看这样的满足长度K的数组有几个
{
res++;
if(um[A[temp]]>1) um[A[temp]]--;
else um.erase(A[temp]);
temp++;
}
while(temp>l)//恢复
{
um[A[temp-1]]++;
temp--;
}
r++;
}
return res;
}
};