128_longest_consecutive_sequence

Leetcode

128. 最长连续序列

shaozkshaozk leetcode/128_longest_consecutive_sequence.cpp · 27 行 · 更新于 2026-09-08

// 128. 最长连续序列
// 给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
// 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> set;
        for (int& num : nums) {
            set.insert(num);
        }
        int result = 0;
        for (const int& num : set) {
            if (!set.count(num - 1)) {
                int cur = num;
                int streak = 1;
                
                while (set.count(cur + 1)) {
                    cur += 1;
                    streak += 1;
                }
                result = max(result, streak);
            }
        }
        return result;
    }
};

评论