Description:
题目大意:给出一个数组,找到最长的连续数字序列。
解题思路:
算法标签:哈希表
- 利用 unordereds_set 将所有元素加入,去重,不需要排序
- 对每个元素依次遍历,前面的元素不存在再访问,因为那样才不连续
代码:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
// 速度更快
unordered_set<int>number;
for(int i = 0;i < nums.size();i++)
number.insert(nums[i]);
int ans = 0;
for(const int& num : number) {
// 前面的数字必须不存在,不然就连在一起了
if(!number.count(num - 1)) {
int currenttnum = num;
int currentlength = 1;
while(number.count(currenttnum + 1)) {
currenttnum += 1;
currentlength += 1;
}
ans = max(ans , currentlength);
}
}
return ans;
}
};