• 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的好些方法在处理大数据量时要慎用呀
  • 相关阅读:
    把office文档转换为html过程中的一些坑
    JAVA运行时问题诊断-工具应用篇
    转:IT公司的十大内耗,别说你公司没有!
    安装storm的一些很乱的笔记
    航伴项目介绍
    centos7防火墙操作
    MySQL 截取字符串
    redis客户端介绍及php客户端的下载安装
    vscode 连接远程服务器 sftp
    redis主从复制
  • 原文地址:https://www.cnblogs.com/okokabcd/p/16593176.html
Copyright © 2020-2023  润新知