题目:330
题意:给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。
题解:贪心算法
主要思想,对于任意x,如果 [1, x) 内所有数字都被覆盖,而且 z 在数组nums中,那么对于任意 1 <= y < x ,则y+z 也被覆盖。那么如果z小于x则 [z , x+z)中的所有数字将被覆盖
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
int ans = 0;
int x = 1;
int index = 0;
while (x <= n) {
if (index < nums.size() && nums[index] <= x) {
x += nums[index++];
}
else {
x *= 2;
ans++;
}
}
return ans;
}
};