给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

核心思想:用 HashSet 去重 + 快速查找,仅从「连续序列起点」开始统计,避免重复计算,实现 O (n) 时间复杂度;
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for ( int num: nums) {
num_set.add(num);
}
int max = 0;
for ( int num: num_set) {
// 关键判断:只有当前数字是「连续序列的起点」时,才开始统计
if (!num_set.contains(num -1 )) {
int currentNum = num;
int currentMax = 1;
while( num_set.contains(currentNum + 1)) {
currentNum ++;
currentMax ++;
}
max = Math.max(max, currentMax);
}
}
return max;
}
}



