leetcode(longest consecutive sequence)

来源:互联网 发布:手机淘宝网充话费 编辑:程序博客网 时间:2024/06/05 16:26

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<unordered_map>
#include<iostream>
#include<vector>
using namespace std;
class solution{
public:
int lc(vector<int> const&num){
unordered_map<int,bool> used;
for(auto i:num) used[i]=false;
int longest=0;
for(auto i:num)
{
if(used[i]) continue;
int length=1;
used[i]=true;
for(int j=i+1;used.find(j)!=used.end();++j)
{
used[j]=true;
++length;
}
for(int j=i-1;used.find(j)!=used.end();--j)
{
used[j]=true;
++length;
}
longest=max(longest,length);
}
return longest;
}
};
int main()
{   
vector<int> coll;
coll.push_back(200);
coll.push_back(4);
coll.push_back(100);
coll.push_back(1);
coll.push_back(3);
coll.push_back(2);
solution s;
cout<<s.lc(coll)<<endl;
}


原创粉丝点击