leetcode 最长连续序列 中等

hash,将每个出现的数都存上。
再一次枚举每一个数 x 作为起点,一直查询 x + i 是否存在。i 能够到达的最大值即是以 x 为起点的最大长度。
然后最重要的一点优化:当 x - 1 不存在时,才有必要枚举 x + i 查询,如果 x - 1 存在,那么它肯定不是最长的。所以最后的时间复杂度是 O(n)
class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<int> have; for(auto &item : nums) have.insert(item); int ans = 0; for(auto &item : have) { if(have.find(item - 1) == have.end()) { int temp = 0; while(have.find(item + temp) != have.end()) ++ temp; ans = max(ans, temp); } } return ans; } };

浙公网安备 33010602011771号