-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path128. Longest Consecutive Sequence.cpp
More file actions
51 lines (47 loc) · 1.16 KB
/
128. Longest Consecutive Sequence.cpp
File metadata and controls
51 lines (47 loc) · 1.16 KB
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
// O(n)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
unordered_set<int> us;
for (int i = 0; i < nums.size(); i++) { // O(n)
us.insert(nums[i]);
}
int lcs = 1;
int c = 0;
int num = 0;
for (auto it : us) {
if (us.find(it - 1) == us.end()) {
c = 1;
num = it;
}
while (us.find(num + 1) != us.end()) {
num++;
c++;
}
lcs = max(c, lcs);
}
return lcs;
}
};
// O(n log n)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
sort(nums.begin(), nums.end()); // O(n log n)
int c = 1, lcs = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i - 1] + 1 == nums[i]) {
c++;
} else if (nums[i - 1] == nums[i]) {
continue;
} else {
lcs = max(c, lcs);
c = 1;
}
}
lcs = max(c, lcs);
return lcs;
}
};