题目链接:128. 最长连续序列 - 力扣(LeetCode)
思路:哈希
将所有数字存入集合中,然后遍历每个数字,检查它是否是某段连续序列的起点(即不存在 num - 1
)。如果是起点,就依次查找后续连续数字的长度,并更新最长序列长度。通过跳过非起点数字,避免了重复计算,提高了效率。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
// 将数组中的数字存入哈希集合
unordered_set<int> numSet(nums.begin(), nums.end());
int longestStreak = 0;
// 遍历数组中的每个数字
for (int num : nums) {
// 检查是否为连续序列的起点
if (!numSet.count(num - 1)) {
int currentNum = num;
int currentStreak = 1;
// 继续向后查找连续数字
while (numSet.count(currentNum + 1)) {
currentNum++;
currentStreak++;
}
// 更新最长连续序列长度
longestStreak = max(longestStreak, currentStreak);
}
}
return longestStreak;
}
};