128_最长连续序列
约 351 字大约 1 分钟
2026-03-08
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9示例 3:
输入:nums = [1,0,1,2]
输出:3解题思路
给定的数组有可能重复,先把数组放入一个 HashSet 里,做去重,再遍历 Set(注意不能遍历原数组,否则会有很多重复数据导致超时)
- 第一个目标:找到所有的序列头 (
num-1不在 Set 里,说明是头) - 第二个目标:如果是头,循环判断
num+1在不在序列里,如果在,max++
注意,可能有多个头,所以需要两个变量:
currentMax表示当前这个头序列长度,例如 【1,2,3,4】 或 【200,201】max表示所有 currentMax 里面,取最大的那个, 例如【1,2,3,4】
Java 实现
import java.util.HashSet;
import java.util.Set;
class Solution {
public int longestConsecutive(int[] nums) {
if (nums.length == 0){
return 0;
}
Set<Integer> set = new HashSet<>();
for (int num : nums){
set.add(num);
}
int max = 0;
for (int curr: set){
int currentMax = 0;
// 如果 curr-1 不在 set 里,说明是头
if (!set.contains(curr - 1)){
while (set.contains(curr++)){
currentMax++;
}
}
max = Math.max(currentMax, max);
}
return max;
}
}