最长连续序列 Java
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet();for (int i : nums) set.add(i);int max = 0;for (int num : set) {if (set.contains(num - 1)) continue; // 上一个数存在,说明当前数不是连续片段的开头int cur = num; // 当前数int curLen = 0; // 当前长度// HashSet加速查找下一个数是否存在,更新最大长度while (set.contains(cur++)) {curLen++;max = Math.max(max, curLen);}}return max;}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~