原题链接:Patching Array - LeetCode
题目
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
Example 1:
Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].
Example 3:
Input: nums = [1,2,2], n = 5
Output: 0
思路
从最小的1开始考虑,如果数组的第一个数不是1,则必须补上1,这时能组合出[1,1]的数。
然后看下一个数,如果大于2,那么2就没有办法用数组里的数表示出来了,所以要补上2,这时能组合出[1, 3]的数;如果下一个数A小于等于2,则把A加入数组,可组合范围就变为[1, 1+A]。
算法
如果遍历到nums[i-1]时,已经可以组合出[1, x]的所有数字,根据nums[i]的值有以下两种情况:
a. 若nums[i]小于等于x+1,我们就把nums[i]加入数组,加入之后就可以组合出[1,x+nums[i]]的数字。
b. 若nums[i]大于x+1,因为把nums[i]加入后不能组合出x和nums[i]之间的数字,所以不能把nums[i]加入数组;这时就需要加入一个新的数字x+1,加入之后可以组合出[1, 2x+1]的数字。
以此类推,直到可组合范围是[1, n]为止。
代码实现
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
edge = 0
i = 0
res = 0
while edge < n:
if i < len(nums) and nums[i] <= edge + 1:
edge += nums[i]
i += 1
else:
edge = edge * 2 + 1
res += 1
return res
复杂度分析
时间复杂度:O(N)
空间复杂度:O(1)