数据结构和算法

2025.04 128. 最长连续序列

2025-09-27  本文已影响0人  wo不是黄蓉

题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked

/** 这道题的难点在于怎么能找到起始点,不能直接从最小的值或者最大值开始查找
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function (nums) {
    // 边界情况
    if (nums.length === 0) return 0;
    
    // 使用 Set 存储所有数字,便于 O(1) 查找
    const numSet = new Set(nums);
    let maxLength = 0;
    
    for (let num of numSet) {
        // 只有当 num 是连续序列的起始点时才开始计算
        // 即 num-1 不在 set 中
        if (!numSet.has(num - 1)) {
            let currentNum = num;
            let currentLength = 1;
            
            // 向右扩展,找连续的数字,找到起始点后开始往后查找,直到找不到为止
            while (numSet.has(currentNum + 1)) {
                currentNum++;
                currentLength++;
            }
            
            // 更新最大长度
            maxLength = Math.max(maxLength, currentLength);
        }
    }
    
    return maxLength;
}

const res = longestConsecutive([100, 4, 200, 1, 3, 2])
console.log(res)

上一篇 下一篇

猜你喜欢

热点阅读