330. 按要求补齐数组
给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/patching-array
思路:
代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
vector<int> nums;
int nu;
int n;
cin >> nu;
nums.push_back(nu);
while (getchar() != '\n') {
cin >> nu;
nums.push_back(nu);
}
cin >> n;
long long index = 0;
int num = 0;
int i = 0;
while (index < n) {
if (i==nums.size()||index+1 < nums[i]) {
num++;
index = index * 2 + 1;
}
else {
index += nums[i];
i++;
}
}
cout << num;
return 0;
}