Featured image of post longestConsecutiveSequence

longestConsecutiveSequence

128. 最长连续序列

算法

  1. 使用哈希集合 (unordered_set):

    • 首先将数组中的所有元素存入一个哈希集合 s 中,便于快速判断某个数字是否存在
  2. 遍历数组,寻找序列起点:

    • 对于每个数字 start,如果 start - 1 不存在于集合中,说明它是某个连续序列的起点
    • 从这个起点开始,逐步检查 start + 1, start + 2, 是否存在于集合中,计算连续序列的长度
  3. 优化:删除已访问元素:

    • 在遍历过程中,一旦某个数字被处理,可以从集合中删除,避免后续重复处理
  4. 更新结果:

    • 记录所有连续序列的最大长度

复杂度分析

时间复杂度

  • 构建哈希集合:O(n) ,其中 n 是数组长度
  • 遍历数组:
    • 每个元素最多被访问两次(一次作为序列起点,一次作为序列中元素)
    • 总复杂度为 O(n)
  • 总时间复杂度为 O(n)

空间复杂度

  • 使用了一个哈希集合存储数组中的所有元素,空间复杂度为 O(n)

C++ 代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
    int longestConsecutive(std::vector<int>& nums)
    {
        std::unordered_set<int> s; // 哈希集合存储所有数字
        for (int num : nums)
            s.insert(num);

        int res = 0; // 记录最长连续序列的长度

        for (int start : nums)
        {
            // 如果 start 是序列的起点(前一个数字不存在)
            if (s.count(start) && !s.count(start - 1))
            {
                int end = start; // 初始化序列的起点
                s.erase(end);    // 移除起点,避免重复处理

                // 找到当前序列的结尾
                while (s.count(end + 1))
                {
                    end += 1;
                    s.erase(end); // 同样移除,优化后续查询
                }

                // 更新最长长度
                res = std::max(res, end - start + 1);
            }
        }

        return res;
    }
};

Python 代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
      hash_set = set(nums)

      res = 0
      for start in nums:
        if start in hash_set and start - 1 not in hash_set:
          end = start
          while end in hash_set:
            hash_set.remove(end)
            end += 1
          res = max(res, end - start)
      return res

Go 代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
func longestConsecutive(nums []int) int {
  hash_set := make(map[int]bool)
  for _, x := range nums {
    hash_set[x] = true
  }

  res := 0
  for _, start := range nums {
    if hash_set[start] && !hash_set[start - 1] {
      end := start
      for hash_set[end] {
        delete(hash_set, end)
        end ++
      }
      if res < end - start {
        res = end - start
      }
    }
  }

  return res
}

JavaScript 代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function (nums) {
  let hash_set = new Set(nums);
  let res = 0;
  for (let start of nums) {
    if (hash_set.has(start) && !hash_set.has(start - 1)) {
      let end = start;
      while (hash_set.has(end)) {
        hash_set.delete(end);
        end++;
      }
      res = Math.max(res, end - start);
    }
  }
  return res;
};
Built with Hugo
Theme Stack designed by Jimmy