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;
    }
相关推荐
wuminyu1 天前
Java世界中StringTable源码剖析
java·linux·c语言·jvm·c++
hairenwangmiao1 天前
B4041 [GESP202409 四级] 区间排序
算法·排序
一个做软件开发的牛马1 天前
Spring Boot 自动配置原理揭秘:从 @SpringBootApplication 到手写自定义 Starter
java·后端
人道领域1 天前
【LeetCode刷题日记】47.全排列Ⅱ
java·开发语言·算法·leetcode
漂流瓶jz1 天前
UVA-1606 两亲性分子 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·向量·aoapc·算法竞赛入门经典·atan2·浮点
Navigator_Z1 天前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<二分查找>1
算法
是苏浙1 天前
Java实现链表1
java·开发语言
未若君雅裁1 天前
上传数据安全:对称加密、非对称加密、签名与重放防护
java·安全
「維他檸檬茶」1 天前
大模型算法学习2026.6.13
学习·算法