LeetCode热题100_最长连续序列

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

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

排序速度快,思路简单,但是时间复杂度高

方法二 哈希表

速度稍微慢了一点

时间复杂度低 O(n)

java 复制代码
/*
     * 最长连续序列
     * 方法一  排序
     * */
    /*public static int longestConsecutive(int[] nums) {
        if (nums.length==0){
            return 0;
        }
        int result = 0;
        int counts = 1;
        Arrays.sort(nums);
        for (int i=1;i< nums.length;i++){
            if (nums[i]==nums[i-1]){
                continue;
            }
            if (nums[i]-(nums[i-1]+1)==0){
                counts++;
            }else{
                //连续中断
                result = Math.max(result,counts);
                counts=1;
            }
        }
        return Math.max(result,counts);
    }*/

    /*
     *  方法二  哈希表
     * */
    public static int longestConsecutive(int[] nums) {
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }
        int longestStreak = 0;
        for (int num:numSet){
            if (!numSet.contains(num-1)){
                int currentNum = num;
                int currentStreak = 1;

                while (numSet.contains(currentNum+1)){
                    currentNum++;
                    currentStreak++;
                }
                longestStreak = Math.max(longestStreak,currentStreak);
            }
        }
            return longestStreak;
    }
相关推荐
m0_5873830015 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
mmmmath_315 小时前
LeetCode.199.二叉树的右视图
数据结构·leetcode
·云扬·15 小时前
Prompt 工程与安全:从 System 设计到注入防御
java·人工智能·安全·ai·prompt
专注仿真15 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸15 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫15 小时前
2028编程圈很火的10个Skills
算法·面试·github
代码不停16 小时前
自动化测试(java)
java·开发语言·selenium·自动化
鬼手点金18 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
paopaokaka_luck19 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts
Wang's Blog19 小时前
Java 项目实战: 交友项目 - Dubbo 的内部结构与一次调用的完整链路
java·dubbo