leetcode 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. 

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

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

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

具体代码也贴上来。

 1 #include <iostream>
 2 #include <map>
 3 using namespace std;
 4 
 5 int main(){
 6     int n;
 7     int length=-1;
 8     int longest=-1;
 9     map<int,bool>f;//f是一个从int到bool的映射
10     map<int,bool>::iterator j;
11     cin>>n;
12     for (int i=1;i<=n;i++){
13         int a;
14         cin>>a;
15         f[a]=true;
16     }
17     for (j=f.begin();j!=f.end();j++){
18         if (j->second==true){
19             j->second=false;
20             length=1;
21             int t=j->first+1;
22             while (f.find(t)!=f.end()){
23                 f[t]=true;
24                 length++;
25                 t++;
26             }
27             t=j->first-1;
28             while (f.find(t)!=f.end()){
29                 f[t]=true;
30                 length++;
31                 t--;
32             }
33             if (longest<length) longest=length;
34         }
35     }
36     cout<<longest<<endl;
37     return 0;
38 }
View Code

 

转载于:https://www.cnblogs.com/iamliyou/p/5357050.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值