本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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.

分析:

算法1:首先想到的是排序,排序后遍历一遍就可以找出最长连续序列的长度,只是要稍微注意下判断连续序列的过程中有可能两个元素相同,比如1 2 2 3,排序复杂度n*log(n),虽然题目要求O(n)复杂度,但是这个解法也可以通过OJ,代码如下:

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int res = 1, len = num.size();
 7         if(len == 0)return 0;
 8         sort(num.begin(), num.end());
 9         int curr = 1;
10         for(int i = 1; i < len; i++)
11         {
12             if(num[i] - num[i-1] == 1)
13             {
14                 curr++;
15                 if(curr > res)res = curr;
16             }
17             else if(num[i] - num[i-1] == 0);
18             else 
19                 curr = 1;
20         }
21         return res;
22     }
23 };
View Code

算法2:想要O(n)的算法,我们只有以时间换空间,先把数组中所有元素映射到哈希表。然后以题目给出的数组为例:对于100,先向下查找99没找到,然后向上查找101也没找到,那么连续长度是1,从哈希表中删除100;然后是4,向下查找找到3,2,1,向上没有找到5,那么连续长度是4,从哈希表中删除4,3,2,1。这样对哈希表中已存在的某个元素向上和向下查找,直到哈希表为空。算法相当于遍历了一遍数组,然后再遍历了一遍哈希表,复杂的为O(n)。代码如下:                            本文地址

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int res = 1, len = num.size();
 7         if(len == 0)return 0;
 8         unordered_set<int> hashtable;
 9         for(int i = 0; i < len; i++)
10             hashtable.insert(num[i]);
11         while(hashtable.empty() == false)
12         {
13             int currlen = 1;
14             int curr = *(hashtable.begin());
15             hashtable.erase(curr);
16             int tmp = curr-1;
17             while(hashtable.empty()==false && 
18                 hashtable.find(tmp) != hashtable.end())
19             {
20                 hashtable.erase(tmp);
21                 currlen++;
22                 tmp--;
23             }
24             tmp = curr+1;
25             while(hashtable.empty()==false && 
26                 hashtable.find(tmp) != hashtable.end())
27             {
28                 hashtable.erase(tmp);
29                 currlen++;
30                 tmp++;
31             }
32             if(res < currlen)res = currlen;
33         }
34         return res;
35     }
36 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3422249.html

posted @ 2013-11-13 21:38  tenos  阅读(1064)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童