128. 最长连续序列
2020-06-06 本文已影响0人
geaus
题目描述
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
解题思路
直接能想到的方式是,先对数组进行排序,然后从头遍历数组找到最长的连续序列,但这样算法复杂度是O(nlogn)。
另外一种思路是,将数组转为hash set,对set中的每个数连续判断num+1,num+2...是否存在,每次访问存在O(1)。但是有个问题需要避免,存在重复判断。所以在访问set的某个数时,需要判断num-1是否存在,如果存在则说明遍历num-1时已经访问num,所以这里就不需要继续访问num。这样的时间复杂度为O(n)。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> nums_set;
for(int val : nums){
nums_set.insert(val);
}
int ret = 0;
for(int val : nums_set){
if(!nums_set.count(val-1)){
int current_length = 1;
int current_num = val;
while(nums_set.count(current_num+1)){
current_length += 1;
current_num += 1;
}
ret = ret>current_length ? ret:current_length;
}
}
return ret;
}
};