一、题目描述
二、解题思路
整体思路:利用map提取所有的key值,按照从小到大的顺序排列,最后使用滑动窗口来求解最长的连续序列的长度。
注意:map的key是有序的,注意滑动窗口越界情况!!!
三、代码实现
cpp
class Solution {
public:
//哈希表+滑动窗口
int longestConsecutive(vector<int>& nums) {
//边界处理
if(nums.empty()) return 0;
//哈希表 <nums[i],bool>
map<int,bool> hash;
for(int num:nums)
hash[num] = true;
//提取出所有的key(从小到大)
vector<int> List;
for(auto [x,x1]:hash)
List.push_back(x);
//滑动窗口
int left,right;
int ret = 1;
for(left=0,right=1;right!=List.size();right++){
//出窗口
if(List[right-1]!=List[right]-1)
left=right;
ret = max(ret,right-left+1);
}
return ret;
}
};
