[128. 最长连续序列]
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
思路:hash表+枚举,我们先用hash Set存储每一个数,再遍历每一个数i
为起始位置时,查找是否存在i+1,i+2,。。。
来找到最大长度,但并不需要枚举每一个i
,对于一个i
如果存在 i-1
,则没有必要枚举它,应为无论如何,它一定包含在 i-1
为起始的序列中,这样就能把时间复杂度控制在O(N);
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int res= 0;
for (int num : nums) {
if(set.contains(num-1)){
continue;
}else {
int max = 1;
while (set.contains(num+1)){
max++;
num++;
}
res = Math.max(res, max);
}
}
return res;
}
}