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.

 

方法一:直接排序数组,然后从第二个元素开始与前面的元素比较,有3种情况:连续,相等,不连续,时间复杂度为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 ans = 1;
 7         int cur = 1;
 8         for(int i=1; i<num.size(); ++i)
 9             if( num[i] - num[i-1] == 1 ) {  //如果是连续的
10                 ++cur;
11                 ans = max(ans, cur);
12             }
13             else if( num[i] - num[i-1] == 0 );  //如果前后元素是相等的
14             else cur = 1;   //如果是不连续的
15         return ans;
16     }
17 };

方法二:空间换时间,直接使用哈希表,将数组元素全部装入哈希表中,这时哈希表有元素100, 4, 200, 1, 3, 2,假设我们访问到了2,发现哈希表中存在2,这时删除2,cur = 1,在向上遍历3,4,哈希表删除3,4,cur为3,再向下遍历1,哈希表删除1,cur为4,此时哈希表存在元素 100,200,cur就是结果的一种可能,代码如下:

 

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         if( num.empty() ) return 0;
 5         unordered_set<int> ust;
 6         for(int i=0; i<num.size(); ++i) //将元素全部插入哈希表中
 7             ust.insert(num[i]);
 8         int ans = 1;
 9         for(int i=0; i<num.size(); ++i)
10             if( ust.find(num[i]) != ust.end() ) {   //如果哈希表中存在num[i]
11                 int cur = 1;
12                 int baseNum = num[i];
13                 ust.erase(baseNum);     //哈希表中删除num[i]
14                 int t = baseNum + 1;
15                 while( ust.find(t) != ust.end() ) {//往上遍历连续的元素,如果存在,cur加1,同时在哈希表中删除元素,表示已经访问过
16                     ++cur;
17                     ust.erase(t++);
18                 }
19                 t = baseNum - 1;
20                 while( ust.find(t) != ust.end() ) {//往下遍历连续的元素
21                     ++cur;
22                     ust.erase(t--);
23                 }
24                 ans = max(ans, cur);
25             }
26         return ans;
27     }
28 };

 

posted on 2014-08-22 16:21  bug睡的略爽  阅读(137)  评论(0编辑  收藏  举报

导航