当前位置:网站首页>力扣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;
}边栏推荐
猜你喜欢

数据可视化(一)

GPU-CUDA-图形渲染分析

使用Windbg过程中两个使用细节分享

Opencv算术操作

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 001-Go语言前提简介

机器学习——逻辑回归

In-depth understanding of timeout settings for Istio traffic management

gradle尚硅谷笔记

【加密解密】明文加密解密-已实现【已应用】

This notebook of concurrent programming knowledge points strongly recommended by Ali will be a breakthrough for you to get an offer from a big factory
随机推荐
Use KUSTO query statement (KQL) to query LOG on Azure Data Explorer Database
Http-Sumggling缓存漏洞分析
如何修改管理工具client_encoding
苹果Meta都在冲的Pancake技术,中国VR团队YVR竟抢先交出产品答卷
华为分析&联运活动,助您提升游戏总体付费
Common operations of oracle under linux and daily accumulation of knowledge points (functions, timed tasks)
化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
.NET in-depth analysis of the LINQ framework (6: LINQ execution expressions)
GPU-CUDA-图形渲染分析
朴素贝叶斯
The host computer develops C# language: simulates the STC serial port assistant to receive the data sent by the microcontroller
.NET深入解析LINQ框架(六:LINQ执行表达式)
学生信息管理系统(第一次.....)
Custom filters and interceptors implement ThreadLocal thread closure
60行从零开始自己动手写FutureTask是什么体验?
Image segmentation model - a combination of segmentation_models_pytorch and albumations to achieve multi-category segmentation
图像分割模型——segmentation_models_pytorch和albumentations 组合实现多类别分割
A small test of basic grammar, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, basic grammar of go lang and the use of variables EP02
【名词】什么是PV和UV?
导火索:OAuth 2.0四种授权登录方式必读