-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path992.cpp
More file actions
25 lines (24 loc) · 719 Bytes
/
992.cpp
File metadata and controls
25 lines (24 loc) · 719 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
return atMostWithKDistinct(nums, k) - atMostWithKDistinct(nums, k - 1);
}
int atMostWithKDistinct(vector<int>& nums, int k){
int res = 0;
int left = 0;
int right = 0;
unordered_map<int, int> count_map;
while (right < nums.size()){
if (count_map[nums[right]] == 0) k--;
count_map[nums[right]]++;
right++;
while (k < 0){
count_map[nums[left]]--;
if (count_map[nums[left]] == 0) k++;
left++;
}
res += right - left + 1;
}
return res;
}
};