Leecode Hot100 刷题笔记本-模拟(C++版)

65 阅读1分钟

128. 最长连续序列

Screen Shot 2023-08-19 at 3.43.04 PM.png

解法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)