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.
一看呢,就是排序,然后找就好了,但是要求是O(n),排序明显是个O(n*logn)的算法.
只是找连续的嘛,我们可以把所有的数字都存入hash表,然后随意从某个数字开始找他的前面和后面那个是否存在.
然后得到一个最大的长度.当然找过的就可以删掉了...你想,一个连续的序列,你从中间任意位置开始往两边找不都一样么.
所以只要找过就可以删掉了.
class Solution {
public:
unordered_set<int> s;
int check(int a, bool direct)
{
int cnt = 0;
for(auto iter = s.find(a); iter != s.end(); iter = s.find(a))
{
s.erase(iter);
if(direct) a--;
else a++;
cnt++;
}
return cnt;
}
public:
int longestConsecutive(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++)
{
s.insert(nums[i]);
}
int ans = 0;
for(int i = 0; i < n; i++)
{
ans = max(ans, check(nums[i], true)+check(nums[i]+1, false));
}
return ans;
}
};