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) complex
使用哈希表,每次访问过一个元素将其置为false
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int,bool> mp;
for(auto i:num)
mp[i]=true;
int maxLength=0;
int right,left,n;
for(auto i:num) {
n=1;
right=i+1;
left=i-1;
while(mp[right]==true){
mp[right++]=false;
n++;
}
while(mp[left]==true){
mp[left--]=false;
n++;
}
maxLength=max(maxLength,n);
}
return maxLength;
}
};