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)的时间复杂度,一般都是用空间换时间,这个题目利用unordered_set比较简单
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> record(nums.begin(),nums.end());
int res=0;
for(int n:nums){
if(record.find(n)==record.end()) continue;
record.erase(n);
int prev=n-1,post=n+1;
while(record.find(prev)!=record.end()) record.erase(prev--);
while(record.find(post)!=record.end()) record.erase(post++);
res=max(res,post-prev-1);
}
return res;
}
};