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;
    }
相关推荐
DongQiShanRen16 小时前
裁决台账双向互校(上):名册与实物的第一道对账
java·linux·运维·数据库·人工智能·自然语言处理·数据挖掘
朝朝辞暮i17 小时前
C++ 第 39 章: 阶段性总复习——类、对象、构造、继承、this、指针与智能指针
开发语言·c++·算法·ros2
cpolar技术支持17 小时前
Spring Boot 接口本地正常,异地前端却报跨域?用 cpolar 跑通 CORS 预检与白名单
java·springboot·cpolar·前后端分离·cors
wuminyu17 小时前
Virtual Thread重投递至ForkJoinPool任务队列过程解析
java·linux·c语言·jvm·c++
垆边人似月.17 小时前
华为题:污染水域
算法
小蒜学长17 小时前
在线保险服务与管理平台的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端·服务平台·在线保险
All for pursuit.17 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
掉进电商坑三年没爬出来的东叔17 小时前
青龙面板进阶:一个面板聚合多平台签到,所有积分自动领
java·开发语言
ZhangJun9517 小时前
Mobike 共享单车分析项目
人工智能·python·算法·kmeans·聚类·knn
Navigator_Z17 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode