044_最长连续序列

知识点:哈希表

LeetCode第一百二十八题:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/

两种解题思路的时空复杂度一样,不过第二种比较容易理解。

语言:GoLang

func longestConsecutive(nums []int) int {
    max := 0
    hMap := map[int]int{}
    for _, value := range nums {
        //  如果存在前驱节点,则忽略。稍后由他的前驱节点来处理这段长度
        if hMap[value] == 0 {
            left, right := hMap[value - 1], hMap[value + 1]

            cur := left + right + 1
            if cur > max {
                max = cur
            }

            // 只更新区间端点的值,区间中间的值不会被取到(因为上述的left与right只获取隔壁的值)
            hMap[value] = cur
            hMap[value - left] = cur
            hMap[value + right] = cur
        }
    }

    return max
}





func longestConsecutive_(nums []int) int {
    length := len(nums)

    hMap := map[int]int{}
    for i := 0; i < length; i++ {
        hMap[nums[i]] = i
    }

    max := 0
    for i := 0; i < length; i++ {
        //  如果存在前驱节点,则忽略。稍后由他的前驱节点来处理这段长度
        if _, ok := hMap[nums[i] - 1]; !ok {
            j := 1
            for ; ; j++ {
                if _, ok := hMap[nums[i] + j]; !ok {
                    break
                }
            }
            if j > max {
                max = j
            }
        }
    }

    return max
}
posted @ 2020-04-04 10:34  Cenyol  阅读(84)  评论(0)    收藏  举报