当前位置: 面试刷题>> 最长连续序列 (经典算法题500道)


题目描述补充

题目:最长连续序列

给定一个未排序的整数数组 nums,找出数字连续的最长序列(至少包含两个数)的长度。要求算法的时间复杂度为 O(n),其中 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

PHP 示例代码

function longestConsecutive($nums) {
    if (empty($nums)) return 0;

    $numSet = array_flip($nums); // 将数组转换为集合以提高查找效率
    $maxLength = 0;

    foreach ($nums as $num) {
        // 如果当前数字减一不在集合中,则当前数字可能是连续序列的起点
        if (!isset($numSet[$num - 1])) {
            $currentNum = $num;
            $currentLength = 1;

            // 查找当前数字开始的连续序列的长度
            while (isset($numSet[$currentNum + 1])) {
                $currentNum++;
                $currentLength++;
            }

            $maxLength = max($maxLength, $currentLength);
        }
    }

    return $maxLength >= 2 ? $maxLength : 0; // 确保返回的长度至少为2
}

// 测试
$nums = [100, 4, 200, 1, 3, 2];
echo longestConsecutive($nums); // 输出 4

Python 示例代码

def longestConsecutive(nums):
    if not nums:
        return 0

    num_set = set(nums)
    max_length = 0

    for num in nums:
        if num - 1 not in num_set:  # 检查是否是连续序列的起点
            current_num = num
            current_length = 1

            while current_num + 1 in num_set:
                current_num += 1
                current_length += 1

            max_length = max(max_length, current_length)

    return max_length if max_length > 1 else 0

# 测试
nums = [100, 4, 200, 1, 3, 2]
print(longestConsecutive(nums))  # 输出 4

JavaScript 示例代码

function longestConsecutive(nums) {
    if (nums.length === 0) return 0;

    const numSet = new Set(nums);
    let maxLength = 0;

    for (let num of nums) {
        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 >= 2 ? maxLength : 0; // 确保返回的长度至少为2
}

// 测试
const nums = [100, 4, 200, 1, 3, 2];
console.log(longestConsecutive(nums)); // 输出 4

码小课:在编程学习的道路上,掌握算法和数据结构是基础而关键的一步。以上代码示例不仅展示了如何解决问题,还体现了在算法设计中如何平衡时间复杂度和空间复杂度的思考。码小课网站中有更多关于算法和数据结构的精彩内容,欢迎大家前往学习交流,共同进步。

推荐面试题