2025.04 128. 最长连续序列

题目链接: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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。