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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
int longestConsecutive(vector<int> &num) {
const int length = num.size();
if (length == 0 || length == 1) return length;
unordered_set<int> s;
for (int i = 0; i < length; ++i)
s.insert(num[i]);
int result = 1, count, temp;
for (int i = 0; i < length; ++i)
if (s.find(num[i]) != s.end()) {
temp = num[i];
s.erase(temp);
count = 1;
while (s.find(temp-1) != s.end()) {
--temp;
++count;
s.erase(temp);
}
temp = num[i];
while (s.find(temp+1) != s.end()) {
++temp;
++count;
s.erase(temp);
}
result = max(result, count);
}
return result;
}
};</span>