128. 最长连续序列
leetcode Hot 100系列
文章目录
- 一、核心操作
- 二、外层配合操作
- 三、核心模式代码
- 总结
一、核心操作
- 将数组转成set,对于set中的每一个元素,判断其前面有没有元素,如果没有则可以判断是连续子序列的第一个,从这里开始往后计数,一直到子序列中断
- res记录最长的序列长度
提示:小白个人理解,如有错误敬请谅解!
二、外层配合操作
- 大循环正常,小循环是在set中遍历
- count可以在哈希表中判断该值存不存在
三、核心模式代码
代码如下:
class Solution {
public:
int longestConsecutive(std::vector<int>& nums) {
int res=0;
std::unordered_set<int> set(nums.begin(),nums.end());
for(const auto& x : set)
{
int temp=x;
if(set.count(temp-1))continue;
else
{
int y=temp+1;
while (set.count(y))
{
y++;
}
if((y-temp)>res)res=y-temp;
}
}
return res;
}
};
总结
- 队首开始数,set中遍历