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;
    }
相关推荐
金銀銅鐵6 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊7 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh8 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj5209 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6610 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
老师我太想进步了202611 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志7832411 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
SL_staff11 小时前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
特立独行的猫A11 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
UIU11411 小时前
P1481 魔族密码
c++·算法·动态规划