From : https://leetcode.com/problems/longest-consecutive-sequence/
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>& nums) {
map<int, bool> has;
int len = nums.size();
for(int i=0; i<len; ++i) {
has[nums[i]] = true;
}
int num = 0;
for(int i=0; i<len; ++i) {
int cur = 1;
if(has[nums[i]]) {
// left
for(int k=nums[i]-1;; --k) {
if(has[k]) {
++cur;
has[k] = false;
} else{
break;
}
}
// right
for(int k=nums[i]+1;; ++k) {
if(has[k]) {
++cur;
has[k] = false;
} else{
break;
}
}
}
if(cur > num) {
num = cur;
}
}
return num;
}
};