# leetcode 最长延续序列 longest consecutive sequence

www.MyException.Cn  网友分享于：2013-09-10  浏览：12次
leetcode 最长连续序列 longest consecutive sequence

1. 预处理：建hashset，将数组元素全部加进hashset里头

2. For each element e in array:

2.1 if e in hashset:

find e-1, e+1 in hashset until cannot go further anymore

remove these elements from hashset

2.2 if the sequence is longer all previous sequences ，update max length

hash_*系列例如hash_map,hash_set 等已经被desperate被废弃了，C++11用unordered_map,unordered_set等来替代。

```class Solution {
public:
int longestConsecutive(vector<int> &num) {

unordered_set<int>::const_iterator it;
unordered_set<int> set;
for(int i=0;i<num.size();i++){
if(set.find(num[i])==set.end()){
set.insert(num[i]);
}
}
int maxc = 0;
for(int i=0;i<num.size();i++){
int c = 1 ;
if(set.find(num[i])!=set.end()){
int cur = num[i]+1;
while(set.find(cur)!=set.end()){
set.erase(cur);
c++;
cur++;

}
cur = num[i]-1;
while(set.find(cur)!=set.end()){
set.erase(cur);
c++;
cur--;
}
if(maxc<c)
maxc=c;

}
}

return maxc;
}
};```