leetcode_128 最长连续序列
1. 题意
给定一组数,求最长连续序列,要求时间复杂度 O ( n ) O(n) O(n)
2. 题解
常规解法肯定是直接排序,再求最长连续序列,但是这样复杂度肯定是
超了的。
因此我们用哈希表来存,之后再求最长连续序列。
一个比较重要的小优化是,如果 v − 1 v-1 v−1在哈希表中,我们就不需要再从
v v v开始枚举最长连续序列了!
class Solution {
public:int longestConsecutive(vector<int>& nums) {std::unordered_set<int> hs;for (int num: nums) {hs.insert( num );}int ans = 0;for (auto it = hs.begin(); it != hs.end(); ++it) {int v = *it;if ( hs.count( v - 1) ) {continue;}int ed = v + 1;while ( hs.count(ed) ) { ed++;}ans = std::max( ans, ed - v);}return ans;}
};