-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestconsecutive.cpp
39 lines (31 loc) · 1 KB
/
longestconsecutive.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
class Solution {
public:
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<int,int> m;
int longest = 0;
for(int i = 0; i < num.size(); i ++){
m[num[i]] = i;
}
for(int i = 0; i < num.size(); i ++){
if(m.find(num[i]) == m.end())
continue;
int lcount = 0, rcount = 0;
int left = num[i] -1, right = num[i] + 1;
while(m.find(left) != m.end()){
lcount++;
m.erase(left);
left --;
}
while(m.find(right) != m.end()){
rcount++;
m.erase(right);
right++;
}
if(lcount+rcount+1 > longest)
longest = lcount+rcount+1;
}
return longest;
}
};