原题网址:https://leetcode.com/problems/patching-array/
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
.
方法:假设对于某个正整数m,能够组合出 [1,m),则如果我们补充一个数字m,意味着能够组合出 [1,m) U m U [1+m, m+m) = [1, m+m)。那么现在的问题是,究竟是需要打补丁,还是从nums中取出数字?我们设置一个指针i,表示nums中最小的未使用的下标元素。即nums[0],nums[1],...,nums[i-1]已经使用过,而nums[i]未使用,这意味着nums[0]~nums[i-1]加上必要的补丁数字,能够组合出 [1,m),如果nums[i]<=m,则引入nums[i],新的组合是 [1,m) U nums[i] U [1+nums[i], m+nums[i])。如果nums[i]==m,则新的组合等价于[1, m+nums[i]);如果nums[i]<m,则新的组合同样等价于 [1, m+nums[i])。
此题我没有做出来,参考网上的:https://leetcode.com/discuss/82822/solution-explanation
public class Solution {
public int minPatches(int[] nums, int n) {
int patches = 0;
long missing = 1;
int i = 0;
while (missing <= n) {
if (i < nums.length && nums[i] <= missing) {
missing += nums[i++];
} else {
missing += missing;
patches ++;
}
}
return patches;
}
}
另一种实现:
public class Solution {
public int minPatches(int[] nums, int n) {
long max = 0;
int patch = 0;
int i=0;
while (max<n) {
while (i<nums.length && nums[i]-1 <= max && max < n) max += nums[i++];
if (max >= n) break;
max += max + 1;
patch ++;
}
return patch;
}
}
再一种实现:
public class Solution {
public int minPatches(int[] nums, int n) {
long max = 0;
int patch = 0;
int i=0;
while (max<n) {
if (i<nums.length && nums[i]-1 <= max) max += nums[i++];
else {
max += max + 1;
patch ++;
}
}
return patch;
}
}