当前位置:网站首页>力扣330 按要求补齐数组(贪心)
力扣330 按要求补齐数组(贪心)
2022-08-05 11:07:00 【这代码有点上头】


这道题主要用到了贪心的思想
设想一个情景,我用一堆数能够表示 [1,x-1]的范围的数
那么我将[1,x-1]范围内的数添加一个进来就能够表示x了
但是上面的并不是最优的,再想想,我们不如添加x吧
因为添加x之后,我能够表示数的范围增大了,增大至[1,2x-1]
而你将[1,x-1]范围内的数添加进来达不到这个效果
所以我们秉承这个思想
我们去遍历nums数组,如果该下标的数<=x 那么我们直接扩大x,表示可表示的范围增大了
如果该下标的数超过了x,我们应该怎么办呢?
没错就是将x加入数组,x->2*x
表示我们可表示的范围增加值2x-1
直到2x>这个数
这样才能保证我中间的数都能连续得被表示
代码附上:
int minPatches(vector<int>& nums, int n) {
int res=0;
long long x=1;
int index=0;
int len=nums.size();
while(x<=n){
if(index<len&&nums[index]<=x){
x+=nums[index];
index++;
}
else{
x<<=1;
res++;
}
}
return res;
}边栏推荐
- Guys, I am a novice. I use flinksql to write a simple count of user visits according to the document, but it ends after executing it once.
- PostgreSQL 2022 Report: Rising popularity, open source, reliability and scaling key
- Opencv算术操作
- What do T and Z in the time format 2020-01-13T16:00:00.000Z represent and how to deal with them
- .NET深入解析LINQ框架(六:LINQ执行表达式)
- Login function and logout function (St. Regis Takeaway)
- 【AGC】增长服务1-远程配置示例
- Linux:记一次CentOS7安装MySQL8(博客合集)
- 如何修改管理工具client_encoding
- Http-Sumggling缓存漏洞分析
猜你喜欢

shell编程流程控制练习

What are the standards for electrical engineering

Android 开发用 Kotlin 编程语言 二 条件控制

PostgreSQL 2022 Report: Rising popularity, open source, reliability and scaling key

硅谷来信:快速行动,Facebook、Quora等成功的“神器”!

Microcontroller: temperature control DS18B20

支持向量机SVM

sqlserver编写通用脚本实现获取一年前日期的方法

Machine Learning - Ensemble Learning

GPU-CUDA-图形渲染分析
随机推荐
软件测试之集成测试
Custom filters and interceptors implement ThreadLocal thread closure
工程设备在线监测管理系统自动预警功能
Opencv算术操作
张朝阳对话俞敏洪:一边是手推物理公式,一边是古诗信手拈来
60行从零开始自己动手写FutureTask是什么体验?
R语言ggplot2可视化:可视化密度图(Density plot)、可视化多个分组的密度图、数据点分布在箱图中间、添加主标题、副标题、题注信息
Import Excel/CSV from Sub Grid within Dynamics 365
如何用Golang来手写一个Blog - Milu.blog 开发总结
Guys, I am a novice. I use flinksql to write a simple count of user visits according to the document, but it ends after executing it once.
机器学习——集成学习
秘乐短视频挖矿系统开发详情
.NET in-depth analysis of the LINQ framework (6: LINQ execution expressions)
低代码平台开发有什么好处?
图像分割模型——segmentation_models_pytorch和albumentations 组合实现多类别分割
Opencv图像缩放和平移
Three methods for extracting facial features
poj2287 Tian Ji -- The Horse Racing(2016xynu暑期集训检测 -----C题)
时间格式2020-01-13T16:00:00.000Z中的T和Z分别表示什么,如何处理
例题 可达性统计+bitset的使用