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;
}

这是一道关于数组填充的问题,目标是通过补充分数到已排序的正整数数组中,确保所有1到n的数字都能被数组中的数字之和表示。题目来源于LeetCode,要求找到满足条件的最少补充数字个数。
最低0.47元/天 解锁文章
278

被折叠的 条评论
为什么被折叠?



