最长连续序列 Java

java 复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet();
        for (int i : nums) set.add(i);
        int max = 0;
        for (int num : set) {
            if (set.contains(num - 1)) continue; // 上一个数存在,说明当前数不是连续片段的开头
            int cur = num; // 当前数
            int curLen = 0; // 当前长度
            // HashSet加速查找下一个数是否存在,更新最大长度
            while (set.contains(cur++)) {
                curLen++;
                max = Math.max(max, curLen);
            }
        }
        return max;
    }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

相关推荐
垆边人似月.4 小时前
华为机试题 :最大数
c++·算法·华为
高级程序源4 小时前
springboot大学生体测系统72170-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
谢亮_vipxieliang4 小时前
JavaScript this 指向完全指南:调用位置决定一切
开发语言·javascript·ecmascript
IT研究室4 小时前
最新计算机毕业设计选题推荐-基于spring boot的文学名著分享系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
denlaku4 小时前
JDK 13 新特性详解
java·开发语言
秋饼4 小时前
Java 后端企业级 LLM 网关实战:Spring Cloud Gateway 构建统一大模型接入层
java·ai·技术分享·后端开发
今年下半年4 小时前
【防重放】Spring Boot 通过自定义注解实现接口防重放
java·spring boot·自定义注解·防重放
念越4 小时前
题库、练习与错题本代码阅读
开发语言·数据结构
WeiXin_DZbishe4 小时前
基于Node.js的马拉松赛事管理系统的设计与实现-计算机毕设 附源码【课程设计】90211
java·javascript·vue.js·python·php·课程设计
l1t4 小时前
几种数据库软件count(distinct)和count()from group by子查询性能测试
开发语言·数据库