【LeetCode】128.最长连续序列

题目

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

提示:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

解答

源代码

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> numSet = new HashSet<Integer>();
        int curLength = 0;
        int maxLength = 0;

        for (int i = 0; i < nums.length; i++) {
            numSet.add(nums[i]);
        }

        for (int num : numSet) {
            if (numSet.contains(num - 1)) {
                continue;
            }

            curLength = 0;

            while (numSet.contains(num)) {
                curLength++;
                num++;
            }

            maxLength = Math.max(maxLength, curLength);
        }

        return maxLength;
    }
}

总结

这题因为需要判断某个数有没有相邻的数存在于数组中,所以需要用到哈希表来进行查询。用set集合存储去重后的数组元素,遍历这个集合,我们需要寻找的是一条序列的第一个值。对于当前元素num,如果num - 1也存在于set集合中,那么num就不是第一个值,集合接着向下遍历;如果num - 1不在set集合中,那么num就可以作为序列的第一个值,接着查询num + 1是否在集合中……这条序列查询结束后,更新最大序列长度。

猜你喜欢

转载自blog.csdn.net/qq_57438473/article/details/131977922