思路
- 将向量转为无序集合,实现去重和快速查找
- 遍历查找需要注意从x开始 而不是x+1 x+2…开始
代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size()==0)
return 0;
//转为hashmset 相同key被合并 即去重
unordered_set<int> hashset;
for(int i:nums)
hashset.insert(i);
int max_length=0,temp,length;
//遍历快速查找
for(int i:hashset){
//要从x开始找 而不是x+1 x+2...
if(hashset.count(i-1)==1)
continue;
temp=i+1;
length=0;
while(hashset.count(temp)==1){
temp++;
length++;
}
max_length=max(length,max_length);
}
return max_length+1;
}
};
本文介绍如何使用C++的unordered_set将整数向量转换为无序集合,以便快速去除重复元素,并通过遍历查找算法找到最长连续序列。重点在于理解从x开始而非x+1的查找策略。
1012

被折叠的 条评论
为什么被折叠?



