128. 最长连续序列
解法1: 哈希表
- 使用
unordered_set去重 - 使用for循环遍历数组, 当
num-1存在则暂时跳过
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set;
for (const int& num : nums) {
num_set.insert(num);
}
int longestStreak = 0;
for (const int& num : num_set) {
if (!num_set.count(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.count(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = max(longestStreak, currentStreak);
}
}
return longestStreak;
}
};
- 时间复杂度: O(N)
- 空间复杂度: O(N)