ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【重点】【哈希】128.最长连续序列

2026/9/11 23:00:17 拓冰建站 浏览量
【重点】【哈希】128.最长连续序列

题目
思路:https://leetcode.cn/problems/longest-consecutive-sequence/solutions/2362995/javapython3cha-xi-biao-ding-wei-mei-ge-l-xk4c/?envType=study-plan-v2&envId=top-100-liked
在这里插入图片描述

class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();for (int num : nums) {set.add(num);}int len = 0, maxLen = 0, tmp;for (int num : set) {tmp = num;if (!set.contains(num - 1)) { // 序列起点len = 1;while (set.contains(++tmp)) {++len;}maxLen = maxLen > len ? maxLen : len;}}return maxLen;}
}