您的位置:首页 > 其它

[Leetcode] 330. Patching Array 解题报告

2017-08-02 17:08 295 查看
题目

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
.
思路

这是一道贪心算法的题目,自己开始也没有想到最优解法。这里将参考的网上解法说明如下:

我们从左往右遍历数组,并且维护一个到当前为止最大可以到达的值。如果当前数组的值比这个最大值大,就说明我们无法合成这个值,需要补贴一个数,然后加上补贴的这个数更新为新的最大可能到达的值。以题目中的测试用例2(nums = [1, 5, 10], n = 20)为例来说明具体过程:

1)初始状态:能够cover的是小于1的数,因此第一个遇到1,正好可以cover下一个数,不需要补贴,这样我们可以更新最大可以cover的值为1*2 = 2以内的数(不包含2)。

2)第二个数是5,而我们现在能够cover的是小于1的数,因此需要补贴一个2,此时更新cover的值为2*2 = 4,即我们可以cover4以内的数(不包含4);然后我们发现依然不能到达5,所以需要在补贴一个4,之后可以到达的数就是8之内的数了(不包含8);再看数组5,因为5已经在可以cover的范围之内了,而多了5好之后,可以cover的最大值就变成了8 + 5 = 13之内的数了(不包含13);此时可以再遍历下一个数了。

3)下一个数组值为10,依然在我们可以cover的范围之内,因此不需要补贴,但是cover的值却可以更新到13 + 10 = 23 > 20,因此就可以返回了。

代码

class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long cover = 1; // now we can make the sums smaller than cover
int result = 0; // the return value
int index = 0; // the current index
while(cover <= n) {
if(index >= nums.size() || nums[index] > cover) { // we need to patch one number now
++result;
cover = cover * 2;
}
else { // we only need to update cover
cover += nums[index];
++index;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: