Leetcode::Longest Consecutive Sequence

Description:

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.

分析:这道题目利用hashmap, 完全没想到。。。。! hashmap可以做到快速查找O(1),当用到大量查找的时候,hashmap不能忘记!

为什么这道题目会用到大量查找呢,因为无序数组还想找连续序列,还要保证O(n)复杂度,即只能遍历数组。则做法就是对一个数,搜索

跟它相邻的那些数,一直搜索到连续链断掉!

这题建立了一个hashmap的键是数组值,那值设为什么呢? 没有值,就可以只用一个unordered_set搞定,但是一个搜索到一个连续链

很多值就已经被用到了,所以为了避免重复,hashmap的值就设为bool,来表示这个值是否被用到。 

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         //build a hashmap to store used-situation
 5         //Expand each element to find its longest subsequence
 6         unordered_map<int,bool> usedrec;
 7         
 8         vector<int>::iterator iter;
 9         for(iter=num.begin();iter!=num.end();iter++)
10             usedrec[*iter] = false;
11         
12         //iter = num.begin();
13         int maxcons = 0;
14         
15         for(iter = num.begin();iter!=num.end();iter++)
16         {
17             if(usedrec[*iter]) continue;
18             int length = 1;
19             
20             //left expand
21             for(int tar = *iter-1;usedrec.find(tar)!=usedrec.end();tar--)
22             {
23                 length++;
24                 usedrec[tar] = true;
25             }
26             //right expand
27             for(int tar = *iter+1;usedrec.find(tar)!=usedrec.end();tar++)
28             {
29                 length++;
30                 usedrec[tar] = true;
31             }
32             
33             maxcons = max(maxcons, length);
34         }
35         return maxcons;
36     }
37 };

 

这道题目当然还有一般的解法,O(nlogn).首先排序,然后找最大链

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         if(num.empty()) return 0;
 5         sort(num.begin(),num.end());
 6         int cons=1,maxcon=1;
 7         for(int i=1;i<num.size();i++)
 8         {
 9             if(num[i]==num[i-1]) continue;
10             if((num[i]-num[i-1])==1) cons++;
11             else{
12                 if(cons > maxcon) maxcon = cons;
13                 cons = 1;
14             }
15         }
16         maxcon = max(cons,maxcon);
17         
18         return maxcon;
19     }
20 };

 

 

posted on 2014-06-07 11:09  soyscut  阅读(173)  评论(0编辑  收藏  举报

导航