Description
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in 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:
nums = [1, 3], n = 6
Return 1.
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:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
解题思路
设置一个 miss 变量表示我们现在未覆盖的最小的数字。因为我们要满足从 1~n 都覆盖,所以设 miss 初始值为 1。
开始循环时,分两种情况考虑,一种是数组里面的数字还没有全都用上,另一种是数组里的数字都用完了。
标注: min 表示数组中未使用过的最小的数字
- 数组里的数字没全用上
比较需要的数字 miss 和数组里没有用的数字中最小的,有三种情况
- miss 更小
这时候数组中没有一个组合可以满足需要的值,需要插入该值,即插入 miss ,这时候覆盖的范围变成了 [1, miss × 2 - 1]。更新 miss 为未覆盖的值,即 miss = miss × 2。 - miss 更大
当前可以表示的范围为 [1, miss - 1],再加上数组里没有使用的最小的值,就可以表示范围 [1, miss + min - 1]。 - 一样大
同 miss 更大的情况。
- miss 更小
- 数组里的数字全都用过
这时候只能通过插值来满足题意,与第一种情况类似。每次插入的值都为 miss,能表示的范围更新为 [1, miss × 2 - 1],再更新 miss 为未覆盖的值,即 miss = miss × 2。
循环直到未覆盖的最小数字 miss 大于我们需要覆盖到的值 n 时终止。
上述思路,整理转化为代码如下。
Code
int minPatches(vector<int>& nums, int n) {
int ans = 0;
int pos = 0;
int length = nums.size();
long miss = 1;
while (miss <= n) {
if (pos < length && nums[pos] <= miss) {
miss += nums[pos++];
} else {
ans++;
miss <<= 1;
}
}
return ans;
}