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:想要O(n)的算法,我们只有以空间换时间,先把数组中所有元素映射到哈希表。然后以题目给出的数组为例:对于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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int res = 1, len = num.size();
if(len == 0)return 0;
unordered_set<int> hashtable;
for(int i = 0; i < len; i++)
hashtable.insert(num[i]);
while(hashtable.empty() == false)
{
int currlen = 1;
int curr = *(hashtable.begin());
hashtable.erase(curr);
int tmp = curr-1;
while(hashtable.empty()==false &&
hashtable.find(tmp) != hashtable.end())
{
hashtable.erase(tmp);
currlen++;
tmp--;
}
tmp = curr+1;
while(hashtable.empty()==false &&
hashtable.find(tmp) != hashtable.end())
{
hashtable.erase(tmp);
currlen++;
tmp++;
}
if(res < currlen)res = currlen;
}
return res;
}
};