欢迎光临
我们一直在努力

128.最长连续序列

给定一个未排序的整数数组 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;

}
}

赞(0)
未经允许不得转载:171主机测评 » 128.最长连续序列
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址