128. 最长连续序列

  1. 最长连续序列
    给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入:nums = 100,4,200,1,3,2

输出:4

解释:最长数字连续序列是 1, 2, 3, 4。它的长度为 4。

示例 2:

输入:nums = 0,3,7,2,5,8,4,6,0,1

输出:9

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> numSet;
        for(auto d:nums) {
            numSet.insert(d);
        }

        int maxLen = 0;
        for(auto d: nums) {
            if(!numSet.count(d-1)) {
                int curLen = 0;
                while(numSet.count(d)) {
                    curLen++;
                    d++;
                }
                maxLen = max(maxLen, curLen);
            }
        }
        return maxLen;

    }
};
相关推荐
WL学习笔记7 分钟前
堆(数据结构)
数据结构·
星空露珠18 分钟前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
极光代码工作室1 小时前
基于SpringBoot的在线博客系统
java·springboot·web开发·后端开发
我是唐青枫1 小时前
Java Spring Security 实战详解:从登录认证到 JWT 权限控制
java·spring
ihuyigui1 小时前
海外签收通知短信接口
android·java·开发语言·前端·数据库·后端
海棠Flower未眠1 小时前
SpringBoot 消息死信队列(荣耀典藏版)
java·数据库·spring boot
暖和_白开水2 小时前
数据分析agent (七):contextvars 模块上下文request_id
java·前端·数据分析
QXWZ_IA2 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel2 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客2 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化