essay

hot100-最长连续序列

#算法

hot100——最长连续序列

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入:nums = [100,4,200,1,3,2]

输出:4

解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]

输出:9

示例 3:

输入:nums = [1,0,1,2]

输出:3

提示:

0 <= nums.length <= 105

-109 <= nums[i] <= 109

解:

func longestConsecutive(nums []int) int {
    numMap := make(map[int]bool, len(nums))
    //把数组中每个元素存在map中,只需要知道它存不存在,所以值用true/false即可
    for _, num := range nums {
        numMap[num] = true
    }
    MaxLength := 0
    //需要知道当前元素(如5)的前一位(4)存不存在,存在则继续往前推,因为我们需要的是连续最长序列,碰到前一位还有的(没有间断的,不是起点)直接跳过
    for num, _ := range numMap {
        if numMap[num-1] {
            continue
        }
        //走到这里说明当前元素前一位没有,可以作为起点
        currentNum := num
        currentLength := 1
        //依次判断后方连续的元素均存在
        for numMap[currentNum+1] {
            currentNum++
            currentLength++
        }
        //将寻找到的连续序列赋值给MaxLength
        if currentLength > MaxLength {
            MaxLength = currentLength
        }
 
    }
    return MaxLength
}
comments如果有不同意见或者补充,直接留在这里。
contact

在别处继续找到我

如果你想聊技术、设计,或者只是打个招呼。

暂未配置外部链接