您的位置:首页 > 其它

330. Patching Array

2016-05-20 09:47 309 查看
iven 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.

这个应该是贪心的思想,假设[1,n)已经满足,那么接下来需要添加的数字就是n。

然后搜索一遍数组,如果数组num[i]的大小是在[1,n)范围内,那么就可以把这个数组加进去,

这个时候[1,n+num[i])的数字都是可以覆盖的;如果num[i]大于n,那么说明至少n

是无法被覆盖的,这个时候就需要把n加进去。

class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int ans=0,i=0;
long sum=0,tmp=1;//题目的数据比较大,会超过int类型的范围,必须用long
while(tmp<=n){
if(i<nums.size()&&nums[i]<=tmp){
sum+=nums[i++];
tmp=sum+1;
}else{
sum+=tmp;
ans++;
tmp=sum+1;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: