LongDz 的数字文墨提案

128. 最长连续序列

2 min

题目

最长连续序列 中等

思路

使用哈希集合去重并快速查找,从每个连续序列的起点开始扩展

复杂度

  • 时间复杂度: O(n)O(n)
  • 空间复杂度: O(n)O(n)

代码

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int>st;
        for(int i = 0 ;i < nums.size();i++){
            st.insert(nums[i]);
        }
        int ans = 0;
        int nowlen = 1;
        for(auto i:st){
            if(!st.count(i-1))
            {
                while(st.count(i+nowlen)){
                    nowlen++;
                }
                ans = max(ans,nowlen);
                nowlen = 1;
            }
        }
    return ans;
    }
    
};