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

Longest Consecutive Sequence leetcode

2014-08-18 13:04 232 查看
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.

给你一个n个数的乱序序列,O(N)找出其中最长的连续序列的长度。

例如给你
[100, 4, 200, 1, 3, 2]
,那么最长的连续序列为
[1, 2, 3, 4]
,所以返回4。

思路:

最简单直接的想法是:将数组排序,然后扫一遍排好序的序列,从中找出最长的即可,这样的话时间是O(nlogn)+O(n),显然不符合题目要求,会超时。

那怎么样不排序就能做出来呢?

我们先抛开算法,想想自己会怎么找,当数组很小,你可以记住所有的数。例如上面的例子。我们自己找的话,看到一个数例如4,我们会下意识的去找有没有3和5,有3那么就会继续找2,以此类推,直到找不到为止,找过的数以后我就不会再去找了,例如1,2,3,4都在找4的时候一起找过了,所以我后面只考虑100,和200,这样每个数其实我只找了一遍。 如果我能够在O(1)的时间判断是否存在一个数,那么我找最长的序列的时间就是O(N)的。现在好办了,如何实现在O(1)的时间查找一个数?Answer:hash table。对,我们只要将数存储在hashmap或者hashset里面就OK了。这里只要用hashset就够了,我们并不需要键值对的映射。好了,伪代码:

1. 预处理:建hashset,将数组元素全部加进hashset里头

2. For each element e in array:

   2.1 if e in hashset:

           find e-1, e+1 in hashset until cannot go further anymore

           remove these elements from hashset

   2.2 if the sequence is longer all previous sequences ,update max length

另外从这一题学到的C++的东西:

hash_*系列例如hash_map,hash_set 等已经被desperate被废弃了,C++11用unordered_map,unordered_set等来替代。

上代码:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> set; // 不能改成hash_set
unordered_set<int>::const_iterator it;
for(int i = 0;i<num.size();i++) {
if(set.find(num[i]) == set.end()) {
set.insert(num[i]);
}
}
int maxLen = 0;
for(int i=0;i<num.size();i++) {
int tmp = 1;
if(set.find(num[i]) != set.end()) {
int cur = num[i] + 1;
while(set.find(cur) != set.end()) {
set.erase(cur);
tmp++;
cur++;

}
cur = num[i]-1;
while(set.find(cur) != set.end()) {
set.erase(cur);
tmp++;
cur--;

}
if(tmp>maxLen)
maxLen = tmp;
}
}
return maxLen;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode