# 330. Patching Array--Avota

### 问题描述:

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.

### 解题思路:

• 若nums[i] <= current , 则把nums[i]用掉（即 i++），同时current更新为current + nums[i];
• 若nums[i] > current，则添加新的元素current，同时current更新为current * 2.

current从1开始
current可能超过int型，需使用long型

### 示例代码:

class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int len = nums.size();
if(len == 0){
return log2(n) + 1;
}

long current = 1;
int i = 0, count = 0;
while(current <= n){
if(i < len  && nums[i] <= current){
current += nums[i];
i++;
}
else{
count++;
current *= 2;
}
}
return count;
}
};
posted @ 2016-03-06 22:10  Avota  阅读(193)  评论(0编辑  收藏  举报