您的位置:首页 > 产品设计 > UI/UE

leetcode longest consecutive sequence

2016-04-05 21:56 423 查看
原问题描述如下。

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.

主要是有复杂度要求?否则的话用数组存下来慢慢查找显然也是可以的。对复杂度要求比较高的,所以用哈希表写。

C++里面有库可以直接用,主要是map里面的几个函数要注意一下使用,当时参考的链接是http://blog.csdn.net/flqbestboy/article/details/8184484

需要注意的就是f是一个映射,f.find每次都要判断是不是f.end,还有遍历哈希表的写法是::iterator j; 这样,这个指针j->first是指元素,j->second=f[j->first].

具体代码也贴上来。

#include <iostream>
#include <map>
using namespace std;

int main(){
int n;
int length=-1;
int longest=-1;
map<int,bool>f;//f是一个从int到bool的映射
map<int,bool>::iterator j;
cin>>n;
for (int i=1;i<=n;i++){
int a;
cin>>a;
f[a]=true;
}
for (j=f.begin();j!=f.end();j++){
if (j->second==true){
j->second=false;
length=1;
int t=j->first+1;
while (f.find(t)!=f.end()){
f[t]=true;
length++;
t++;
}
t=j->first-1;
while (f.find(t)!=f.end()){
f[t]=true;
length++;
t--;
}
if (longest<length) longest=length;
}
}
cout<<longest<<endl;
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: