# LeetCode128：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.

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

/*
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> &num) {
if(num.empty())
return 0;
unordered_set<int> iset;
vector<int>::iterator iter;
for(iter = num.begin(); iter != num.end(); ++iter)
iset.insert(*iter);

int max = 0;
for(iter = num.begin(); iter != num.end(); ++iter)
{
if(iset.count(*iter) == 1)
{
int c = 1;
int g = *iter + 1;
while(iset.count(g) == 1)
{
iset.erase(g);//找到后记得要删除，不然会重复做，超时
c++;
g++;
}
int l = *iter - 1;
while(iset.count(l) == 1)
{
iset.erase(l);
c++;
l--;
}
if(max < c)
max = c;

}

}
return max;
}
};
int main(void)
{
int arr[] = {100, 4, 200, 1, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> num(arr, arr+n);
Solution solution;
int max = solution.longestConsecutive(num);
cout<<max<<endl;
return 0;
}
-----------------------我和我追猪的梦-----------------------------------------------------------------

posted @ 2014-04-25 18:50  mickole  阅读(260)  评论(0编辑  收藏  举报