forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounting-elements.cpp
More file actions
34 lines (32 loc) · 819 Bytes
/
counting-elements.cpp
File metadata and controls
34 lines (32 loc) · 819 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
26
27
28
29
30
31
32
33
34
// Time: O(n)
// Space: O(n)
class Solution {
public:
int countElements(vector<int>& arr) {
unordered_set<int> lookup(cbegin(arr), cend(arr));
return count_if(cbegin(arr), cend(arr),
[&lookup](const auto& x) {
return lookup.count(x + 1);
});
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
int countElements(vector<int>& arr) {
sort(begin(arr), end(arr));
int result = 0, l = 1;
for (int i = 0; i + 1 < arr.size(); ++i) {
if (arr[i] == arr[i + 1]) {
++l;
continue;
}
if (arr[i] + 1 == arr[i + 1]) {
result += l;
}
l = 1;
}
return result;
}
};