LeetCode 题解工作台
大于等于顺序前缀和的最小缺失整数
给你一个下标从 0 开始的整数数组 nums 。 如果一个前缀 nums[0..i] 满足对于 1 的所有元素都有 nums[j] = nums[j - 1] + 1 ,那么我们称这个前缀是一个 顺序前缀 。特殊情况是,只包含 nums[0] 的前缀也是一个 顺序前缀 。 请你返回 nums 中没有…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们先求出数组 的最长顺序前缀和 ,然后从 开始枚举整数 ,如果 不在数组 中,那么 就是答案。这里我们可以用哈希表来快速判断一个整数是否在数组 中。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 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 <= 501 <= nums[i] <= 50
解题思路
方法一:模拟 + 哈希表
我们先求出数组 的最长顺序前缀和 ,然后从 开始枚举整数 ,如果 不在数组 中,那么 就是答案。这里我们可以用哈希表来快速判断一个整数是否在数组 中。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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).