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
.
补丁数组,题目大意为给定一个数组nums[],以及一个整数n。问需要向nums[]中最少添加几个数,使得能用nums[]中的数来表示[1,n]之间的所有整数。nums[]中使用的数不能重复。
解题思路:给定一个变量bound,表示目前不能表示的最大数值,即此时nums[]可以表示的数为[0,bound)。开始时,将其初始化为1,因为0没有意义。如果这时遇到一个数nums[i],nums[i]<=bound,则加上nums[i]后,其可以表示的数的范围就变成了[0,bound+nums[i])。原先可以表示0~(bound-1),现在是0~(bound-1+nums[i])。如果nums[i]>bound,那么此时需添加一个数,为了能最大限度的增加表示范围,我们加上bound本身,则可以将表示的数扩展到0~(bound+bound)。举例说明:
给定nums = [1, 2, 4, 11, 30], n = 50,我们需要让[0, 50]之间所有的数字都能被nums中的数字之和表示出来。
首先使用1, 2, 4可能表示出0到7之间的所有数,表示范围为[0, 8),但我们不能表示8,因为下一个数字11太大了,所以我们要在数组里加上一个8,此时能表示的范围是[0, 16),那么我们需要插入16吗,答案是不需要,因为我们数组有1和4,可以组成5,而下一个数字11,加一起能组成16,所以有了数组中的11,我们此时能表示的范围扩大到[0, 27),但我们没法表示27,因为30太大了,所以此时我们给数组中加入一个27,那么现在能表示的范围是[0, 54),应经满足要求了,我们总共添加了两个数8和27,所以返回2即可。java算法如下:
public class Solution {
public int minPatches(int[] nums, int n) {
long bound=1;
int add=0;
int i=0;
int size=nums.length;
while(bound<=n){
if(i<size&&nums[i]<=bound){
bound+=nums[i];
i++;
}else{
bound+=bound;
add++;
}
}
return add;
}
}
参考:http://www.bubuko.com/infodetail-1345277.html