LeetCode 题解工作台
按要求补齐数组
给定一个已排序的正整数数组 nums , 和一个正整数 n 。 从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。 请返回 满足上述要求的最少需要补充的数字个数 。 示例 1: 输入: nums = [1,3]…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 贪心·invariant
答案摘要
我们假设数字 是最小的不能表示的正整数,那么 的这些数都是可以表示的。为了能表示数字 ,我们需要添加一个小于等于 的数: - 如果添加的数等于 ,由于 的数都可以表示,添加 后,区间 内的数都可以表示,最小的不能表示的正整数变成了 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给定一个已排序的正整数数组 nums ,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。
请返回 满足上述要求的最少需要补充的数字个数 。
示例 1:
输入: nums =[1,3], n =6输出: 1 解释: 根据 nums 里现有的组合[1], [3], [1,3],可以得出1, 3, 4。 现在如果我们将2添加到 nums 中, 组合变为:[1], [2], [3], [1,3], [2,3], [1,2,3]。 其和可以表示数字1, 2, 3, 4, 5, 6,能够覆盖[1, 6]区间里所有的数。 所以我们最少需要添加一个数字。
示例 2:
输入: nums =[1,5,10], n =20输出: 2 解释: 我们需要添加[2,4]。
示例 3:
输入: nums =[1,2,2], n =5输出: 0
提示:
1 <= nums.length <= 10001 <= nums[i] <= 104nums按 升序排列1 <= n <= 231 - 1
解题思路
方法一:贪心
我们假设数字 是最小的不能表示的正整数,那么 的这些数都是可以表示的。为了能表示数字 ,我们需要添加一个小于等于 的数:
- 如果添加的数等于 ,由于 的数都可以表示,添加 后,区间 内的数都可以表示,最小的不能表示的正整数变成了 。
- 如果添加的数小于 ,不妨设为 ,由于 的数都可以表示,添加 后,区间 内的数都可以表示,最小的不能表示的正整数变成了 。
因此,我们应该贪心地添加数字 ,这样可以覆盖的区间更大。
我们用一个变量 记录当前不能表示的最小正整数,初始化为 ,此时 是空的,表示当前没有任何数可以被覆盖;用一个变量 记录当前遍历到的数组下标。
循环进行以下操作:
- 如果 在数组范围内且 ,说明当前数字可以被覆盖,因此将 的值加上 ,并将 的值加 。
- 否则,说明 没有被覆盖,因此需要在数组中补充一个数 ,然后 更新为 。
- 重复上述操作,直到 的值大于 。
最终答案即为补充的数的数量。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
x = 1
ans = i = 0
while x <= n:
if i < len(nums) and nums[i] <= x:
x += nums[i]
i += 1
else:
ans += 1
x <<= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m + log n) where m is the length of nums and log n accounts for patches, since each patch doubles the reachable sum. Space complexity is O(1) extra space, using only variables to track coverage and patch count. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if candidates understand the greedy invariant principle in sum coverage.
- question_mark
Listen for reasoning about why adding the smallest missing number extends coverage optimally.
- question_mark
Observe if they track 'miss' correctly and iterate efficiently without recalculating sums.
常见陷阱
外企场景- error
Trying to test all subset sums explicitly, which is too slow for large n.
- error
Failing to update 'miss' correctly after adding a patch, leading to incorrect counts.
- error
Assuming adding any number works rather than the minimal missing number, causing suboptimal patching.
进阶变体
外企场景- arrow_right_alt
Modify the problem to track which specific numbers need patching, not just the count.
- arrow_right_alt
Restrict patches to only odd numbers or powers of two, testing adaptation of the greedy strategy.
- arrow_right_alt
Ask for the maximum sum achievable with a fixed number of patches instead of minimal patch count.