forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
happy-students.cpp
40 lines (38 loc) · 972 Bytes
/
happy-students.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
// Time: O(n)
// Space: O(n)
// codeforce, https://codeforces.com/contest/1782/problem/B
// freq table
class Solution {
public:
int countWays(vector<int>& nums) {
vector<int> cnt(size(nums) + 1);
for (const auto& x : nums) {
++cnt[x];
}
int result = 0;
for (int i = 0, prefix = 0; i <= size(nums); ++i) {
if (prefix == i && cnt[i] == 0) {
++result;
}
prefix += cnt[i];
}
return result;
}
};
// Time: O(nlogn)
// Space: O(1)
// codeforce, https://codeforces.com/contest/1782/problem/B
// sort, greedy
class Solution2 {
public:
int countWays(vector<int>& nums) {
sort(begin(nums), end(nums));
int result = 0;
for (int i = 0; i <= size(nums); ++i) {
if ((i == 0 || nums[i - 1] < i) && (i == size(nums) || nums[i] > i)) {
++result;
}
}
return result;
}
};