Longest Consecutive Sequence

本文介绍了一种寻找整数数组中最长连续元素序列的算法,并详细阐述了如何利用unordered_set容器实现O(n)时间复杂度的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题来源

问题描述

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

问题分析

假如不限制时间复杂度的话,实际上我们可以通过排序的形式求解此题。但关键是被套上了 O(n)的限制,问题的难点也在于此。我们可以有这样一种方法:遍历此数组,假设检索的当前元素为n,我们每次都检索 n-1 是否在此数组。这里存在的一个问题是,假如我们使用数组进行检索,那么算法的复杂度仍然为 O(n^2)。因此,我们使用unodered_set容器来存放元素(不适用set的原因是剔除其排序复杂度的影响)。假如 n-1 不在数组中,此时我们便开始检索 从n开始的连续元素数目。最终得到结果。需要解释的是,unordered_set的查找操作是可以在常数时间内完成的。

解决代码

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> sto(nums.begin(), nums.end());
        int r = 0;
        for (auto ele : nums) {
            if (sto.find(ele-1) == sto.end()) {
                int t = 0;
                while (sto.find(ele++) != sto.end()) t++;
                r = max(r, t);
            }
        }
        return r;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值