-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.cc
More file actions
42 lines (35 loc) · 1007 Bytes
/
LongestConsecutiveSequence.cc
File metadata and controls
42 lines (35 loc) · 1007 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
35
36
37
38
39
40
41
42
#include <unordered_set>
using namespace std;
namespace LongestConsecutiveSequence {
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> set;
for (int i = 0; i < num.size(); i++) {
set.insert(num[i]);
}
int max = 0;
for (int i = 0; i < num.size(); i++) {
int cur = num[i];
int left = cur - 1;
int right = cur + 1;
set.erase(cur);
int count = 1;
while(set.find(left) != set.end()) {
set.erase(left);
count++;
left--;
}
while(set.find(right) != set.end()) {
set.erase(right);
count++;
right++;
}
if (max < count) {
max = count;
}
}
return max;
}
};
}