Skip to content

Commit a1dc91d

Browse files
authored
Create 992. Subarrays with K Different Integers
1 parent 27473b7 commit a1dc91d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int findAtMostK(int n, int k, vector<int>&nums){
4+
int ans = 0;
5+
int left = 0, right = 0;
6+
unordered_map<int, int>mp;
7+
while(right<n){
8+
if(mp.find(nums[right])==mp.end()){
9+
mp[nums[right]] = 1;
10+
}
11+
else{
12+
mp[nums[right]]++;
13+
}
14+
15+
while(mp.size()> k && left<=right){
16+
mp[nums[left]]--;
17+
if(mp[nums[left]]==0){
18+
mp.erase(nums[left]);
19+
}
20+
left++;
21+
}
22+
ans += right-left+1;
23+
right++;
24+
}
25+
return ans;
26+
}
27+
int subarraysWithKDistinct(vector<int>& nums, int k) {
28+
int n = nums.size();
29+
return findAtMostK(n, k, nums) - findAtMostK(n, k-1, nums);
30+
}
31+
};
32+
auto init = [](){
33+
ios::sync_with_stdio(false);
34+
cin.tie(nullptr);
35+
cout.tie(nullptr);
36+
return 'c';
37+
}();

0 commit comments

Comments
 (0)