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:
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].
给出一个数组,和一个n,让在数组中填上元素,使数组中的数相加可以得到1~n的所有的数
另外数组中的数不能重复使用(如果能重复使用的话1可以解决所有问题)
思路:
首先举个例子:
[1, 2, 3, 4], 这里面的数任意组合,可以得到的和是1~7,即 < 4*2
(1+4=5, 2+4=6,3+4=7)
一般性推广(此处n代表最后一个元素):
数组[1, 2, 3, … , n-1, n]中
1~(n-1)依次和n相加,可以得到n+1, n+2, …, 2n-1
包含前面的1~n的数,可以表示1~(2n-1)范围的数
因此1~n的数组中元素任意相加,最大可以表示到2n-1的数,即边界<2n
可以得知上述[1, 2, 3, 4]数组可以表示1~4*2-1的范围
这时候如果再来一个元素5,即5 < 现数组可以加到的最大范围(2n-1)= 7
那么只需要将1~(2n-1)依次和5相加,可以得到1~(2n - 1) + 5的范围
这时候如果来一个10,即10 > 现数组可以加到的最大范围(2n-1)= 7
可以看到就算10不和任何数相加,也最小是10,而前面的数组最大只能加到7,中间的8和9是无法得到的,因此这个时候就需要补充元素8,然后因为8的加入,最大可以表示到(2n - 1) = 15, 因此9就不需要再加了
回到题目(此处n是题目中的n):
[1, 5, 10] n= 20
因为数组是sorted的,所以从左到右,先是1,1可以表示的范围到 < 2 * 1, 即 < 2
下一个元素5, 5 >= 最大边界2(不包含2),所以中间的2,3,4无法得到,这时候先补充2, 2的加入使边界更新到 < 2 * 2, 即4(注意不包含4)
5 仍然 >= 4, 所以再补充4,更新边界到 < 2 * 4, 即8(不包含8)
5现在 < 8, 就可以用1~8依次和5相加,得到最大边界是 < 5+8 = 13
5使用完之后读入下一元素10, 10 < 13, 更新最大边界到10 + 13 = 23
而n=20,包含在最大边界23内,因此得到结果,只需要补充2,4即可
注意出错点:
如果n是最大整数(Integer.MAX_VALUE),为了追求这个n,会不断补充元素并更新边界直到>n,如果边界取Integer型, 会产生整数溢出,变成负值,然后就会endless loop,所以注意边界curMax要取long
index超出数组时的处理:直接补充元素并更新边界
思路是这样的:
while(curMax <= n) {
if (index >= nums.length) {
补充curMax元素,更新边界curMax到curMax*2
} else {
if (nums[index] < curMax) {
更新边界到curMax + nums[index]
} else if (nums[index] > curMax) { //边界不含curMax本身
补充curMax元素,更新边界curMax到curMax*2
} else if(nums[index] == curMax) { //nums[index]自己就是边界点
更新边界curMax到curMax*2 (因为相等,也可以表达为nums[index] + curMax)
}
}
简化后得如下代码:
public int minPatches(int[] nums, int n) {
long curMax = 1;
int index = 0;
int res = 0;
while (curMax <= n) {
if (index >= nums.length || nums[index] > curMax) {
res ++;
curMax *= 2;
} else {
curMax += nums[index];
index ++;
}
}
return res;
}