LeetCode 力扣 热题 100道(十九)最长连续序列(C++)

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

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

cpp 复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> numSet(nums.begin(), nums.end()); 
        int longestStreak = 0;
        for (int num : numSet) {
            if (numSet.find(num - 1) == numSet.end()) {
                int currentNum = num;
                int currentStreak = 1;
                while (numSet.find(currentNum + 1) != numSet.end()) {
                    currentNum++;
                    currentStreak++;
                }
                longestStreak = max(longestStreak, currentStreak);
            }
        }
        
        return longestStreak;
    }
};
  • 去重 :首先将输入的数组 nums 转换为哈希集合 numSet,这样就去除了重复的元素,并且能够在常数时间内检查元素是否存在。
  • 查找最长连续序列 :
    • 对于每一个数字 num,我们检查 num - 1 是否存在于集合中。如果不存在,说明 num 是某个连续序列的起始元素。
    • 然后从 num 开始,逐个检查 num + 1, num + 2, ... 是否存在于集合中,直到遇到不存在的元素。
  • 更新最长序列长度 :在每次查找完一个序列后,更新 longestStreak 以记录目前为止找到的最长连续序列的长度。
相关推荐
h39743 小时前
DirectShow过滤器开发-视频源过滤器
c++·windows·音视频·directshow
程序猿编码5 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客6 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆7 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光7 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
信奥卷王7 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵7 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
SuperByteMaster8 小时前
wfi进入之前没有清除basepri, 导致中断优先级不够,wfi 退不出来
c语言
徐小黑ACG8 小时前
Golang 基础05 结构体struct
开发语言·算法·golang