给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
解析:使用哈希表存储所有数字,对每一个数字进行判断:它前面的数字是否存在,如果不存在则尝试判断它之后的数字是否存在,并得到结果。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(!nums.size()) return 0;
unordered_set<int> s(nums.begin(),nums.end());
int res = 0;
for(auto i:nums){
if(!s.count(i-1)){
int next = i+1;
while(s.count(next)) ++next;
res =max(next - i,res);
}
}
return res;
}
};