给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定不同的子数组为好子数组。
(例如,[1,2,3,1,2] 中有 3 个不同的整数:1,2,以及 3。)
返回 A 中好子数组的数目。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarrays-with-k-different-integers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
unordered_map<int, int> S1, S2;
int res = 0;
for (int i = 0, j1 = 0, j2 = 0, cnt1 = 0, cnt2 = 0; i < nums.size(); i ++ ) {
if (!S1[nums[i]]) cnt1 ++ ;
S1[nums[i]] ++ ;
while (cnt1 > k) {
S1[nums[j1]] -- ;
if (!S1[nums[j1]]) cnt1 -- ;
j1 ++ ;
}
if (!S2[nums[i]]) cnt2 ++ ;
S2[nums[i]] ++ ;
while (cnt2 >= k) {
S2[nums[j2]] -- ;
if (!S2[nums[j2]]) cnt2 -- ;
j2 ++ ;
}
res += j2 - j1;
}
return res;
}
};
作者:yxc
链接:https://www.acwing.com/activity/content/code/content/2013434/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。