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.
利用一个hash表去存储这个数组,对于hash表中的元素,可以去查找比他大的相邻的元素,以及比他小相邻的元素,进而确定最长连续串。
以题目给出的数组为例:对于100,先向下查找99没找到,然后向上查找101也没找到,那么连续长度是1,从哈希表中删除100;然后是4,向下查找找到3,2,1,向上没有找到5,那么连续长度是4,从哈希表中删除4,3,2,1。这样对哈希表中已存在的某个元素向上和向下查找,直到哈希表为空。算法相当于遍历了一遍数组,然后再遍历了一遍哈希表,复杂的为O(n)
class Solution {
public:
int longestConsecutive(vector<int> &num) { unordered_set<int> hash;
unordered_set<int>::iterator it; for(int i=;i<num.size();i++) hash.insert(num[i]); int count;
int result=;
while(!hash.empty())
{
count=; it=hash.begin();
int num0=*it;
hash.erase(num0); int num=num0+;
while(hash.find(num)!=hash.end())
{
count++;
hash.erase(num);
num++;
} num=num0-;
while(hash.find(num)!=hash.end())
{
count++;
hash.erase(num);
num--;
} if(result<count) result=count;
} return result;
}
};