【重点】【哈希】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;
    }
}

你可能感兴趣的:(力扣Top100,哈希算法,算法)