LeetCode128. 最长连续序列

☆☆☆☆思路:哈希表。参考  官方题解

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int res = 0;
        for (int num : nums) {
            // 避免从 x+1 或 x+2...等开始匹配,这样得到的结果肯定小于从x开始的
            if (!set.contains(num - 1)) {
                int len = 1; // 当前序列的长度
                // 对每个数x,以其为起点,不断枚举 x+1,x+2...是否存在
                while (set.contains(num + 1)) {
                    num += 1;
                    len += 1;
                }
                res = Math.max(res, len);
            }
        }
        return res;
    }
}

  时间复杂度为O(n),空间复杂度为O(n)

时间复杂度分析:只有当一个数是连续序列的第一个数的情况下才会进入内层循环,然后在内层循环中匹配连续序列中的数,因此数组中的每个数只会进入内层循环一次。因此,总时间复杂度为 O(n)。

 

原文地址:https://www.cnblogs.com/HuangYJ/p/14232785.html