leetcode 128. Longest Consecutive Sequence 最长连续序列(中等)

一、题目大意

https://leetcode.cn/problems/longest-consecutive-sequence

给定一个未排序的整数数组 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 <= 105
-109 <= nums[i] <= 109

二、解题思路

可以把所有数字放到一个哈希表,然后不断地从哈希表中任意取一个值,并删除掉其之前之后的所有连续数字,然后更新目前的最长连续序列长度。重复这一过程,就可以找到所有的连续数字序列,顺便找出最长的。

三、解题方法

3.1 Java实现-超时版

public class Solution1 {
    public int longestConsecutive(int[] nums) {
        Set<Integer> intSet = new HashSet<>();
        for (int num : nums) {
            intSet.add(num);
        }
        int ans = 0;
        while (!intSet.isEmpty()) {
            int cur = intSet.stream().findFirst().get();
            intSet.remove(cur);
            int pre = cur - 1;
            int next = cur + 1;
            while(intSet.contains(pre)) {
                intSet.remove(pre--);
            }
            while(intSet.contains(next)) {
                intSet.remove(next++);
            }
            ans = Math.max(ans, next - pre - 1);
        }
        return ans;
    }
}

3.2 Java实现-通过版

public class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> intSet = new HashSet<>();
        for (int num : nums) {
            intSet.add(num);
        }
        int ans = 0;
        for (int num : nums) {
            if (intSet.remove(num)) {
                int pre = num - 1;
                int next = num + 1;
                while (intSet.remove(pre)) {
                    pre--;
                }
                while (intSet.remove(next)) {
                    next++;
                }
                ans = Math.max(ans, next - pre - 1);
            }
        }
        return ans;
    }
}

四、总结小记

  • 2022/8/16 Map的好些方法在处理大数据量时要慎用呀
posted @   okokabcd  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-08-16 leetcode 167. Two Sum II - Input Array Is Sorted 两数之和 II - 输入有序数组
2018-08-16 归约与分组 - 读《Java 8实战》
点击右上角即可分享
微信分享提示