给定一个非递减数组,以及n,求最小添加几个元素能保证通过元素组合
作者:
敲一手烂代码 | 来源:发表于
2017-03-20 14:58 被阅读6次// 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.
public static int minPatches(int[] nums, int n) {
long miss = 1;
int added = 0, i = 0;
while (miss <= n) {
if (i < nums.length && nums[i] <= miss) {
miss += nums[i++];
} else {
added++;
miss += miss;
}
}
return added;
}
本文标题:给定一个非递减数组,以及n,求最小添加几个元素能保证通过元素组合
本文链接:https://www.haomeiwen.com/subject/ugzbnttx.html
网友评论