forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subarrays-with-k-different-integers.cpp
72 lines (65 loc) · 1.62 KB
/
subarrays-with-k-different-integers.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Time: O(n)
// Space: O(k)
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return atMostK(A, K) - atMostK(A, K - 1);
}
private:
int atMostK(const vector<int>& A, int K) {
int result = 0, left = 0;
unordered_map<int, int> count;
for (int right = 0; right < A.size(); ++right) {
++count[A[right]];
while (count.size() > K) {
if (!--count[A[left]]) {
count.erase(A[left]);
}
++left;
}
result += right - left + 1;
}
return result;
}
};
// Time: O(n)
// Space: O(k)
class Solution2 {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
Window window1, window2;
int result = 0, left1 = 0, left2 = 0;
for (const auto& i : A) {
window1.add(i);
while (window1.size() > K) {
window1.remove(A[left1]);
++left1;
}
window2.add(i);
while (window2.size() >= K) {
window2.remove(A[left2]);
++left2;
}
result += left2 - left1;
}
return result;
}
private:
class Window {
public:
void add(int x) {
++count_[x];
}
void remove(int x) {
--count_[x];
if (count_[x] == 0) {
count_.erase(x);
}
}
size_t size() const {
return count_.size();
}
private:
unordered_map<int, int> count_;
};
};