-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest_Consecutive_Sequence.cpp
49 lines (41 loc) · 1.14 KB
/
Longest_Consecutive_Sequence.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
41
42
43
44
45
46
47
48
49
/*
Problem:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
*/
class Solution {
public:
int longestConsecutive(vector<int> &num)
{
if (num.size() == 0) return 0;
unordered_set<int> ht;
for (int i = 0; i < num.size(); i++)
{
ht.insert(num[i]);
}
int length = 1;
for (int i = 0; i < num.size(); i++)
{
int cur_length = 0;
int cur_num = num[i];
while (ht.count(cur_num))
{
ht.erase(cur_num);
cur_length++;
cur_num++;
}
cur_num = num[i] - 1;
while (ht.count(cur_num))
{
ht.erase(cur_num);
cur_length++;
cur_num--;
}
length = max(length, cur_length);
}
return length;
}
};