一面麦克风有问题 没交流的下去挂
二面手写快排秒了, 一道hard题目没做到O(n)
改编自 992. K 个不同整数的子数组
转换滑动窗口,问题改位求区间内最多只包含k个数的子数组的个数,那么由单调性给以由滑动窗口解决,
对于给定j,满足要求子数组的个数从第一个满足要求的i,到j,共j-i个,因此代码如下:
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return subarraysWithMostKDistinct(A, K) - subarraysWithMostKDistinct(A, K-1);
return 0;
}
// 最多包含k个数的的好子数组个数
// 最多包含k-1个数的好子数组个数
int subarraysWithMostKDistinct(vector<int>& A, int K){
unordered_map<int,int> hashmap;
int count = 0, res = 0;
for(int i = 0, j = 0; j < A.size(); j++){
if(hashmap[A[j]]==0){
count++;
}
hashmap[A[j]]++;
while(count>K){
hashmap[A[i]]--;
if(hashmap[A[i]]==0){
count--;
}
i++;
}
res+= (j-i);
}
return res;
}
};