Skip to content

128.Longest Consecutive Sequence

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.

c++
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int ret = 0;
        unordered_set<int> s;
        for (int i = 0; i < nums.size(); ++i) {
            s.insert(nums[i]);
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (!s.count(nums[i] - 1)) {
                int cnt = 1; 
                int tmp = nums[i] + 1;
                int j = 1;
                for (; s.count(nums[i]+j) > 0;++j) {}
                ret = max(ret, j);
            }
        }
        return ret;
    }
};

基于 VitePress 构建