LeetCode【128】最长连续序列

题目:

分析:

1、最长连续序列的长度为 y-x+1,如1-4:4-1+1 = 4

2、不要被这里的On误导,不敢使用双层循环

3、只要找到最小的数值,并由此开始计算,不产生重复计算,则为On

代码:

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

        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!set.contains(nums[i] - 1)) {
                int y = nums[i] + 1;
                while (set.contains(y)) {
                    y++;
                }
                max = Math.max(max, y-nums[i]);
            }
        }

        return max;
    }
相关推荐
你撅嘴真丑4 小时前
第九章-数字三角形
算法
曹牧4 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
uesowys5 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder5 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮5 小时前
AI 视觉连载1:像素
算法
爬山算法5 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
智驱力人工智能5 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
kfyty7255 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎5 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄5 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea