力扣-128.最长连续序列
题目链接
128.最长连续序列
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();for (int i = 0; i < nums.length; i++) {set.add(nums[i]);}int res = 0;for (int i : set) {if (!set.contains(i - 1)) {int count = 1;int num = i;while (set.contains(num + 1)) {num++;count++;}res = Math.max(res, count);}}return res;}
}
小结:统计连续最长序列长度的时候只从最小的数字开始,保证时间复杂度O(n)
,注意数组中可能有重复,所以直接遍历set
即可。