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.
这道题貌似在陈利人的微博上看到过,当时是有思路的:即采用hash的方法。但是再一次的看到的时候完全不知道怎么做了。
思路应该是这样的:先从头到尾建立hash,然后,从第一个值开始,++看看在不在里面,--看看在不在hash里面。如果在的话,计数,并继续前面的过程。查找完的数要删除掉。
代码同样未实现,下面是别人的代码:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_set<int> map;
int n = num.size();
for(int i = 0;i < n; ++i){
map.insert(num[i]);
}
int max = 1;
for(int i = 0; i< n; ++i){
if(map.find(num[i]) != map.end()){
int temp = 1;
int cur = num[i];
map.erase(cur);
temp += getCount(map, cur + 1, true);
temp += getCount(map, cur - 1, false);
max = temp > max ? temp : max;
}
}
return max;
}
int getCount(unordered_set<int> &map, int cur, bool asc){
int count = 0;
while(map.find(cur) != map.end()){
map.erase(cur);
count ++;
if(asc)
cur++;
else
cur--;
}
return count;
}
};