Solution 1
【参考官方】本题要求线性时间复杂度,因此排序+双指针的思路不能用了,因此需要哈希表上线了。主要的问题在于如何解决一个真的连续的序列如何解决。
官方的思路挺巧妙的(本质上是我的问题……),如果一个数字是另外一个数字的后继,那么一定在较小数字计数时被考虑,因此可以被跳过,而跳过的依据可以翻回来变成:其存在前序数字。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为数字个数,需要将所有数字纳入哈希表,并且需要遍历一次
- 空间复杂度: O ( N ) O(N) O(N),其中 N N N为数字个数,哈希表占用
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
// 遍历一次,插入到哈希表
unordered_set<int> hashmap;
for (int & num: nums) {
hashmap.insert(num);
}
int ans = 0;
for (const int & num: hashmap) {
// 如果不存在前序节点,从头计数
if (hashmap.find(num - 1) == hashmap.end()) {
int now = num;
int temp = 1;
while (hashmap.find(now + 1) != hashmap.end()) {
now++;
temp++;
}
ans = max(ans, temp);
}
}
return ans;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
hashmap= set(nums)
ans = 0
for num in nums:
if num - 1 not in hashmap:
now = num
temp = 1
while now + 1 in hashmap:
now += 1
temp += 1
ans = max(ans, temp)
return ans