当前位置:网站首页>LeetCode每日一题:搜索插入位置 (均1200道)方法:二分查找
LeetCode每日一题:搜索插入位置 (均1200道)方法:二分查找
2022-08-09 01:13:00 【那人独钓寒江雪.】
题目如下:
代码如下:
解题思路:标签:二分查找
如果该题目暴力解决的话需要 O(n)O(n) 的时间复杂度,但是如果二分的话则可以降低到 O(logn)O(logn) 的时间复杂度
整体思路和普通的二分查找几乎没有区别,先设定左侧下标 left 和右侧下标 right,再计算中间下标 mid
每次根据 nums[mid] 和 target 之间的大小进行判断,相等则直接返回下标,nums[mid] < target 则 left 右移,nums[mid] > target 则 right 左移
查找结束如果没有相等值则返回 left,该值为插入位置
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] == target) {
return mid;
} else if(nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}
边栏推荐
猜你喜欢
微信企业号开发之获取AccessToken
全文翻译:EDPB数据保护影响评估(DPIA:Data Protection Impact Assessment)指南
任务六 特征衍生 案例分析
猿辅导联合多方专家共议新课标:语文将更强调“实践性”
Using MySQL in Ubuntu/Linux environment: Modify the database sql_mode to solve the "this is incompatible with sql_mode=only_full_group_by" problem
Use Ehcache distributed cache to easily create commercial-grade high-concurrency, high-performance API interfaces!
JSON basics, transfer JSON data, and introduce four mainstream frameworks, jackson, gson, fastjson, and json-lib!
容器运维平台的故障处理-1
【C语言刷题】链表中快慢指针的应用
425 Can‘t open data connection for transfer of “/“
随机推荐
非科班毕业生,五面阿里:四轮技术面 +HR 一面已拿 offer
卷积神经网络EfficentNet v1学习记录--Model Scaling
4-1 Matplotlib库 数据分析常用图
4-7 Matplotlib库 箱线图
"Replay" interview BAMT came back to sort out 398 high-frequency interview questions to help you get a high salary offer
浅谈自定义应用层协议与UDP的报文结构和注意事项
[Signal denoising] Based on Sage-Husa adaptive Kalman filter to realize the suppression of ocean wave magnetic field noise and the generation of ocean wave magnetic field noise with matlab code
JD.com was abused on three sides. Regarding redis, high concurrency, and distributed, I am confused.
《Go语言学习:基本变量与类型》
EfficientNet v2网络学习记录--更小更快
Pytorch预训练模型和修改——记录
5-2 Seaborn 分类绘图
在vscode中编辑、编译、下载Keil工程
面试秘籍 | 软件测试必备的mysql数据库技术
JSON basics, transfer JSON data, and introduce four mainstream frameworks, jackson, gson, fastjson, and json-lib!
睿智的目标检测61——Tensorflow2 Focal loss详解与在YoloV4当中的实现
【Seata】分布式事务Seata入门与实战
在实际工作中如何开展性能测试?
4-4 Matplotlib库 直方图
Oracle最后一个商用免费版本JDK1.8.202