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;
    }
相关推荐
天天爱吃肉821817 分钟前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
alphaTao28 分钟前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
sino爱学习29 分钟前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
甄心爱学习31 分钟前
【leetcode】判断平衡二叉树
python·算法·leetcode
颜酱41 分钟前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL1 小时前
day50 单调栈
数据结构·算法·leetcode
风生u1 小时前
activiti7 详解
java
岁岁种桃花儿1 小时前
SpringCloud从入门到上天:Nacos做微服务注册中心(二)
java·spring cloud·微服务
Word码1 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
@––––––1 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划