当前位置:网站首页>330. 按要求补齐数组
330. 按要求补齐数组
2022-07-29 06:05:00 【小卢要刷力扣题】
前言
给定一个已排序的正整数数组 nums ,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。
请返回 满足上述要求的最少需要补充的数字个数 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/patching-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
先给数组排序
range代表已经凑出来的数
如果range+1<arr[i],证明还缺数
那么我们只需在range的基础上加一个range+1,直到凑出arr[i]
如果已经凑出arr[i],则在range上加上arr[i]
如果已经遍历完arr,还没有凑出aim,
则不断在range的基础上加range+1,直到凑出aim
代码
class Solution {
public int minPatches(int[] arr, int aim) {
int ans=0;
long range=0;
Arrays.sort(arr);
for(int i=0;i<arr.length;i++){
//要求没被满足
while(arr[i]-1>range){
range+=range+1;
ans++;
if(range>=aim){
return ans;
}
}
range+=arr[i];
if(range>=aim){
return ans;
}
}
while(range+1<=aim){
range+=range+1;
ans++;
}
return ans;
}
}
边栏推荐
- Talk about tcp/ip protocol? And the role of each layer?
- 模拟卷Leetcode【普通】172. 阶乘后的零
- Thread - thread safety - thread optimization
- vscode通过remotessh结合xdebug远程调试php解决方案
- 王树尧老师运筹学课程笔记 05 线性规划与单纯形法(概念、建模、标准型)
- 线程同步—— 生产者与消费者、龟兔赛跑、双线程打印
- IDEA中实现Mapper接口到映射文件xml的跳转
- 猜数字//第一次使用生成随机数
- 10 frequently asked JVM questions in interviews
- Unity免费元素特效推荐
猜你喜欢

Connecting PHP 7.4 to Oracle configuration on Windows

竣达技术 | 适用于”日月元”品牌UPS微信云监控卡

Ali gave several SQL messages and asked how many tree search operations need to be performed?

实战!聊聊如何解决MySQL深分页问题

vscode通过remotessh结合xdebug远程调试php解决方案

Apisik health check test

MutationObserver文档学习

Thread synchronization - producers and consumers, tortoise and rabbit race, dual thread printing

Teacher wangshuyao's notes on operations research 04 fundamentals of linear algebra

Share some tips for better code, smooth coding and improve efficiency
随机推荐
Actual combat! Talk about how to solve the deep paging problem of MySQL
Improved Pillar with Fine-grained Feature for 3D Object Detection论文笔记
【C语言刷LeetCode】67. 二进制求和(E)
Share some tips for better code, smooth coding and improve efficiency
Revolution of game assets
王树尧老师运筹学课程笔记 08 线性规划与单纯形法(单纯形法)
MySql基础知识(高频面试题)
vscode通过remotessh结合xdebug远程调试php解决方案
1172. 餐盘栈 有序列表+栈
数据库持久化+JDBC数据库连接
如何优雅的写 Controller 层代码?
buck电路boot电容短路和断路实测波形
SDN topology discovery principle
Idea cannot find a database solution
Windows 上 php 7.4 连接 oracle 配置
谷歌零碎笔记之JWT(草稿)
The core of openresty and cosocket
Simulation volume leetcode [ordinary] 172. Zero after factorial
吴恩达老师机器学习课程笔记 03 线性代数回顾
基于C语言实现图书借阅管理系统