最长连续序列

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

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

/**
 * @param {number[]} nums
 * @return {number}
 */
const longestConsecutive = (nums = [0, 1, 2, 4, 8, 5, 6, 7, 9, 3, 55, 88, 77, 99, 999999999]) => {
    const length = nums.length
    if (length === 0 || length === 1) return length
    nums.sort((x, y) => x - y)
    let len = 1
    let startIdx = 1
    for (let i = 1; i < nums.length; i++) {
        const pre = nums[i - 1]
        const cur = nums[i]
        if (cur - pre === 1) {
            startIdx += 1
            len = startIdx > len ? startIdx : len
        } else if (cur === pre) {
            continue
        } else {
            startIdx = 1
        }
    }
    return len
};

  

posted @ 2023-02-01 13:19  671_MrSix  阅读(8)  评论(0编辑  收藏  举报