解题思路
要求时间复杂度为 O(n),所以不能用sort
如果有一个x, x+1, x+2, x+y的连续序列,我们只会以x为起点向后枚举,而不会从x+1,x+2,向后枚举。因此判断x-1存在即可。
- 1.定义一个哈希表hash,将nums数组中的数都放入哈希表中。
- 2.遍历哈希表hash,如果当前数x的前驱x-1不存在,我们就以当前数x为起点向后枚举。
- 3.枚举到了数y,连续序列长度为y-x+1。
- 4.更新答案。
代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hash;
for(auto x : nums) hash.insert(x);//把这个数组放入哈希
int res = 0;
for(auto x : hash){//遍历哈希表
if(hash.count(x) && !hash.count(x - 1)){//当前数x的前驱x-1不存在
int y = x;//以当前数x为起点
while(hash.count(y+1)) y++;//向后枚举
res = max(res,(y-x+1));//更新结果
}
}
return res;
}
};