330. 按要求补齐数组

这是一道关于数组填充的问题,目标是通过补充分数到已排序的正整数数组中,确保所有1到n的数字都能被数组中的数字之和表示。题目来源于LeetCode,要求找到满足条件的最少补充数字个数。
摘要由CSDN通过智能技术生成

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值