LeetCode 刷题【128. 最长连续序列】

128. 最长连续序列

自己做

解1:排序

java 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums.length == 0)
            return 0;

        //排序
        Arrays.sort(nums);

        int max = 1;
        int len = 1;

        for(int i = 1; i < nums.length; i++){
            if(i > 1 && nums[i] == nums[i - 1])
                nums[i - 1] = nums[i - 2];
            else if(nums[i] == nums[i - 1] + 1)
                len++;
            else
                len = 1;

            if(len > max)
                max = len;
        }

        return max;
    }
}

看题解

java 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> num_set = new HashSet<Integer>();
        for (int num : nums) {
            num_set.add(num);
        }

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}
相关推荐
知识浅谈8 小时前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
蒸汽求职8 小时前
跨越 CRUD 内卷:半导体产业链与算力基建下的软件工程新生态
人工智能·科技·面试·职场和发展·软件工程·制造
DeepModel8 小时前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊8 小时前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
简简单单做算法10 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
guygg8810 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄10 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec10 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉
yu859395811 小时前
MATLAB连续线性化模型预测控制(SL-MPC)
算法·机器学习·matlab
ytttr87311 小时前
基于ACADO工具包的自主车道跟踪与避障MPC控制
算法