Skip to content

Commit 385943b

Browse files
authored
Update subarrays-with-k-different-integers.cpp
1 parent ad3a49b commit 385943b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/subarrays-with-k-different-integers.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,32 @@
22
// Space: O(k)
33

44
class Solution {
5+
public:
6+
int subarraysWithKDistinct(vector<int>& A, int K) {
7+
return atMostK(A, K) - atMostK(A, K - 1);
8+
}
9+
10+
private:
11+
int atMostK(const vector<int>& A, int K) {
12+
int result = 0, left = 0;
13+
unordered_map<int, int> count;
14+
for (int right = 0; right < A.size(); ++right) {
15+
++count[A[right]];
16+
while (count.size() > K) {
17+
if (!--count[A[left]]) {
18+
count.erase(A[left]);
19+
}
20+
++left;
21+
}
22+
result += right - left + 1;
23+
}
24+
return result;
25+
}
26+
};
27+
28+
// Time: O(n)
29+
// Space: O(k)
30+
class Solution2 {
531
public:
632
int subarraysWithKDistinct(vector<int>& A, int K) {
733
Window window1, window2;

0 commit comments

Comments
 (0)