当前位置:网站首页>二分法 | 35. 搜索插入位置
二分法 | 35. 搜索插入位置
2022-06-10 02:02:00 【lee2813】
一、题目

二、题解
二分法的时候,退出循环的条件为left > right,但是总是存在着left == middle 或 right == middle 的情况。当left == middle时,说明right < middle,即 nums[middle] > target,反之同理。此时即可得到要插入的位置下标为righ的值,反之同理。
三、代码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int middle;
while(left <= right){
middle = left + right;
if(nums[middle] == target ){
return middle;
}else if(nums[middle] > target){
right = middle - 1;
}else{
left = middle + 1;
}
}
if(right < 0){
right = 0;
}
return left > middle ? left : right;
}
};
边栏推荐
- CSP 202104-1 gray histogram
- Latex doesn't break lines. Strange
- Screen resolution
- 正则表达式的边界问题。
- 35 year old workplace anxiety, more and more people choose this
- [win] the browser cannot open the web page and DNS appears_ PROBE_ FINISHED_ NO_ INTERNET
- [FPGA] day15 serial port protocol UART loopback project
- Why does chip design also need "Craftsmanship"?
- mysql路径添加至系统环境变量(win10)
- 2022 mobile crane driver test questions simulation test platform operation
猜你喜欢

CSP 202112-1 序列查询(详解)

Multi task learning

10个常见触发IO瓶颈的高频业务场景

Unity Netcode for GameObject 1.0.0 学习笔记(一)—— Hello World Demo

“无法访问 您可能没有权限使用网络资源”解决办法

服务器停止响应是什么意思,该如何排查?

Catering e-procurement scheme: procurement cycle management, saving 30% of the cost

CSP 202112-1 sequence query (detailed explanation)

WPS adjust text spacing

2、自然语言处理入门
随机推荐
Cordova website packaging_ Cordova packaging website
(w10)Prtsc截图键无法正常使用——解决办法
OpenSUSE auto mount hard disk
28. How much do you know about subject management?
[email protected] -808 and [email protected] -223 introduction
[untitled]
餐饮电子采购方案:采购全周期管理,节省30%成本
Smart cloud light gateway service to improve production management efficiency
Stepper motor summary
LABVIEW_课堂笔记 随机(十三)子VI
CSP 202104-1 灰度直方图
Flutter series: foundation of material theme - materialapp
Leetcode 98: validate binary search tree
Customized page (e.g. website map) button beautification tutorial at the bottom of WordPress website
MongoDB 学习整理(概念解析)
Mongodb learning and sorting (concept analysis)
Unity netcode for GameObject 1.0.0 learning notes (I) - Hello World demo
Implementing nested sliding boxes in unity
Smart Cloud Light Gateway Service pour améliorer l'efficacité de la gestion de la production
[program life] "stage summary" - at a loss