leetcode hot100刷题日记——36.最长连续序列
解答:
实际上在哈希表中存储不重复的数字。
然后遍历哈希表,找间隔,更新最大间隔。
class Solution {
public:int longestConsecutive(vector<int>& nums) {unordered_set<int>hash;for(int num:nums){hash.insert(num);}int longest=0;for(int h:hash){if(!hash.count(h-1)){int cur_num=h;int cur_length=1;while(hash.count(cur_num+1)){cur_num++;cur_length++;}longest=max(longest,cur_length);}}return longest;}
};
时间复杂度:O(n)
空间复杂度:O(n)