LeetCode 题解工作台

大于等于顺序前缀和的最小缺失整数

给你一个下标从 0 开始的整数数组 nums 。 如果一个前缀 nums[0..i] 满足对于 1 的所有元素都有 nums[j] = nums[j - 1] + 1 ,那么我们称这个前缀是一个 顺序前缀 。特殊情况是,只包含 nums[0] 的前缀也是一个 顺序前缀 。 请你返回 nums 中没有…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们先求出数组 的最长顺序前缀和 ,然后从 开始枚举整数 ,如果 不在数组 中,那么 就是答案。这里我们可以用哈希表来快速判断一个整数是否在数组 中。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 。

如果一个前缀 nums[0..i] 满足对于 1 <= j <= i 的所有元素都有 nums[j] = nums[j - 1] + 1 ,那么我们称这个前缀是一个 顺序前缀 。特殊情况是,只包含 nums[0] 的前缀也是一个 顺序前缀

请你返回 nums 中没有出现过的 最小 整数 x ,满足 x 大于等于 最长 顺序前缀的和。

 

示例 1:

输入:nums = [1,2,3,2,5]
输出:6
解释:nums 的最长顺序前缀是 [1,2,3] ,和为 6 ,6 不在数组中,所以 6 是大于等于最长顺序前缀和的最小整数。

示例 2:

输入:nums = [3,4,5,1,12,14,13]
输出:15
解释:nums 的最长顺序前缀是 [3,4,5] ,和为 12 ,12、13 和 14 都在数组中,但 15 不在,所以 15 是大于等于最长顺序前缀和的最小整数。

 

提示:

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 50
lightbulb

解题思路

方法一:模拟 + 哈希表

我们先求出数组 numsnums 的最长顺序前缀和 ss,然后从 ss 开始枚举整数 xx,如果 xx 不在数组 numsnums 中,那么 xx 就是答案。这里我们可以用哈希表来快速判断一个整数是否在数组 numsnums 中。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def missingInteger(self, nums: List[int]) -> int:
        s, j = nums[0], 1
        while j < len(nums) and nums[j] == nums[j - 1] + 1:
            s += nums[j]
            j += 1
        vis = set(nums)
        for x in count(s):
            if x not in vis:
                return x
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate correctly identifies the sequential prefix and calculates its sum.

  • question_mark

    The candidate demonstrates a clear approach to finding missing integers using efficient data structures.

  • question_mark

    The candidate optimizes the problem-solving process by considering edge cases and handling array traversal effectively.

warning

常见陷阱

外企场景
  • error

    Incorrectly identifying the longest sequential prefix due to faulty array traversal.

  • error

    Failing to calculate the sum of the sequential prefix properly.

  • error

    Not considering how to find missing integers efficiently, either by skipping hash table usage or miscalculating the sum.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider implementing the solution with sorting and scanning instead of using hash tables.

  • arrow_right_alt

    Test the problem with an array of maximum size (50) to evaluate the solution's efficiency.

  • arrow_right_alt

    Investigate edge cases with minimal input (i.e., a single element array).

help

常见问题

外企场景

大于等于顺序前缀和的最小缺失整数题解:数组·哈希·扫描 | LeetCode #2996 简单