题目(来自leetcode):算法
给你一个n个数的乱序序列,O(N)找出其中最长的连续序列的长度。数组
例如给你[100, 4, 200, 1, 3, 2]
,那么最长的连续序列为[1, 2, 3, 4]
,因此返回4。.net
思路:code
最简单直接的想法是:将数组排序,而后扫一遍排好序的序列,从中找出最长的便可,这样的话时间是O(nlogn)+O(n),显然不符合题目要求,会超时。blog
那怎么样不排序就能作出来呢?排序
我 们先抛开算法,想一想本身会怎么找,当数组很小,你能够记住全部的数。例如上面的例子。咱们本身找的话,看到一个数例如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就够了,咱们并不须要键值对的映射。好了, 伪代码:element
1. 预处理:建hashset,将数组元素所有加进hashset里头leetcode
2. For each element e in array:rem
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>::const_iterator it; unordered_set<int> set; for(int i=0;i<num.size();i++){ if(set.find(num[i])==set.end()){ set.insert(num[i]); } } int maxc = 0; for(int i=0;i<num.size();i++){ int c = 1 ; if(set.find(num[i])!=set.end()){ int cur = num[i]+1; while(set.find(cur)!=set.end()){ set.erase(cur); c++; cur++; } cur = num[i]-1; while(set.find(cur)!=set.end()){ set.erase(cur); c++; cur--; } if(maxc<c) maxc=c; } } return maxc; } };