128. Longest Consecutive Sequence

class Solution {
public:
    int longestConsecutive(vector<int>& nums)
    {
        unordered_set<int> st(nums.begin(), nums.end());
        int res = 0;
        for(auto& num : nums)
        {
            // 如果是連續數字的話,避免重複計算
            if(st.count(num - 1)) continue;

            int cur = num;
            int length = 1;
            while(st.count(cur + 1))
            {
                ++cur; ++length;
            }
            res = max(res, length);
        }
        return res;
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)