【LeetCode】128. 最长连续序列

leetcode

 

💡 解题思路

​​核心目标​​:在未排序数组中找出数字连续的最长序列长度(不要求元素在数组中连续),时间复杂度必须为 O(n)。
​​关键策略​​:利用哈希集合实现 O(1) 时间复杂度的元素查找,通过识别连续序列的起点(即不存在前驱元素 num-1),向后扩展计算序列长度。

⚙️ 关键步骤

  1. ​​哈希集合初始化​​
    将数组元素存入哈希集合(map[int]bool),实现去重和 O(1) 查找。
  2. ​​识别序列起点​​
    遍历集合,若元素 num 的前驱 num-1 不存在,则 num 是序列起点。
  3. ​​扩展序列长度​​
    从起点向后查找连续数字(num+1, num+2...),统计序列长度。
  4. ​​更新最大值​​
    比较并记录最长序列长度。

⏱ 复杂度分析

步骤时间复杂度空间复杂度说明
哈希集合构建 O(n) O(n) 存储所有元素
序列起点检测 O(n) O(1) 每个元素最多访问两次
序列扩展 O(n) O(1) 嵌套循环但元素不重复访问
​​总计​​ ​​O(n)​​ ​​O(n)​​ 满足题目要求

🚀 代码实现

func longestConsecutive(nums []int) int {
    // 边界处理:空数组直接返回0
    if len(nums) == 0 {
        return 0
    }

    // 初始化哈希集合
    numSet := make(map[int]bool)
    for _, num := range nums {
        numSet[num] = true
    }

    maxLength := 0
    // 遍历哈希集合中的每个数字
    for num := range numSet {
        // 检查是否为序列起点(前驱不存在)
        if !numSet[num-1] {
            currentNum := num
            currentLength := 1

            // 向后扩展序列
            for numSet[currentNum+1] {
                currentNum++
                currentLength++
            }

            // 更新最大长度
            if currentLength > maxLength {
                maxLength = currentLength
            }
        }
    }

    return maxLength
}

💎 代码解析

  1. ​​哈希集合构建​​
    numSet := make(map[int]bool) 创建哈希集合,存储所有不重复元素。
  2. ​​起点检测逻辑
    if !numSet[num-1] 确保只从序列起点开始扩展,避免重复计算。
  3. ​​序列扩展​​
    for numSet[currentNum+1] 向后查找连续数字,实时更新当前序列长度。
  4. ​​性能优化点​​
    • ​​去重处理​​:哈希集合自动过滤重复元素
    • ​​快速失败​​:仅起点触发序列扩展,减少无效操作

📊 执行示例

func main() {
    fmt.Println(longestConsecutive([]int{100, 4, 200, 1, 3, 2}))         // 4
    fmt.Println(longestConsecutive([]int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1})) // 9
    fmt.Println(longestConsecutive([]int{1, 0, 1, 2}))                   // 3
}

🌟 优势总结

    • ​​严格 O(n) 时间复杂度​​:每个元素最多被访问两次(起点检测 + 序列扩展)
    • ​​空间换时间​​:哈希集合实现 O(1) 查找,比排序法(O(n log n))更高效
    • ​​边界鲁棒性​​:显式处理空数组和重复元素场景
posted @ 2025-06-02 12:53  云隙之间  阅读(36)  评论(0)    收藏  举报