128. 最长连续序列

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

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

solution : 

    用一个set集合存所有元素,然后遍历每一个元素,如果当前元素n 有n-1在set集合种,那么不计数,没有就从n计数找最长连续子序列

    

复制代码
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> uset(nums.begin(), nums.end());
        int result = 0;
        for (auto n : nums) {
            if (uset.find(n - 1) == uset.end()) {
                int num = n;
                int count = 1;
                while (uset.find(num + 1) != uset.end()) {
                    ++num;
                    ++count;
                }
                result = max(count, result);
            }
        }
        return result;
    }
};
复制代码

 

posted @   tuffy_tc  阅读(11)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示