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

本文介绍了如何利用哈希表在O(n)时间复杂度内解决LeetCode上的最长连续序列问题。通过建立数字集合,遍历数组删除连续数字并更新最长序列长度,最终找到最长连续序列。提供了两种Java实现,其中一种超时,另一种通过了测试。在处理大数据量时,需要注意哈希表某些操作的效率。
摘要由CSDN通过智能技术生成

一、题目大意

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的好些方法在处理大数据量时要慎用呀
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值