【leetcode】 128. 最长连续序列

73 阅读1分钟

leetcode-128.png

借用set来解决

找到序列的开头(第5行
然后开始逐步向后寻找 +1
保存最大的长度

var longestConsecutive = function (nums) {
    let set = new Set(nums)
    let res = 0
    for (let num of nums) {
        if (!set.has(num - 1)) {
            let current = num
            let currentMax = 1
            while (set.has(current + 1)) {
                current += 1
                currentMax += 1
            }
            res = Math.max(res, currentMax)
        }
    }
    return res
};

使用hash来解决

每次循环找到当前数字的左右可拓展的长度,然后将其存起来(map存

[3,2,4,5,100,101]  

例如对于这个数组来说,首先3进去,然后将map更新为

[{3:3},{2:3},{4:3}]  

然后2还有4进去,直接略过,再到5,此时获取到hash.get(5-1) = 3 更新maxLength = 3 + 1 = 4
这里更新的都是边界上最长的长度,所以当一个没有出现在map里面的数字出现的时候,存在相邻的数字,也就是代码的六、七行,在这里进行更新拓展。

var longestConsecutive = function (nums) {
    let hash = new Map()
    let res = 0
    for (let num of nums) {
        if (!hash.has(num)) {
            let left = hash.get(num - 1) || 0
            let right = hash.get(num + 1) || 0
            // 分别找出左、右最长连续的长度 + 自身
            let maxLength = right + left + 1
            hash.set(num, maxLength)
            hash.set(num - left, maxLength)
            hash.set(num + right, maxLength)
            res = Math.max(res, maxLength)
        }
    }
    return res
};