当前位置:网站首页>LeetCode_35(搜索插入位置)
LeetCode_35(搜索插入位置)
2022-07-01 04:37:00 【***】
题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104 nums 为 无重复元素 的 升序 排列数组
-104 <= target <= 104
class Solution {
public int searchInsert(int[] nums, int target) {
int res=-1;
int left=0,right=nums.length-1,pos=0;
while(left<=right){
pos=(left+right)/2;
if(target>nums[pos])left=pos+1;
else if(target<nums[pos])right=pos-1;
else if(target==nums[pos])return pos;
if(left>right)return left;
}
return res;
}
}
边栏推荐
- How do I sort a list of strings in dart- How can I sort a list of strings in Dart?
- 1. Mobile terminal touch screen event
- Pytorch(一) —— 基本语法
- Basic usage, principle and details of session
- 总结全了,低代码还需要解决这4点问题
- Odeint and GPU
- Leecode record 1351 negative numbers in statistical ordered matrix
- [ue4] event distribution mechanism of reflective event distributor and active call event mechanism
- Pytorch(二) —— 激活函数、损失函数及其梯度
- Software testing needs more and more talents. Why do you still not want to take this path?
猜你喜欢
Task04 | statistiques mathématiques
扩展-Fragment
I also gave you the MySQL interview questions of Boda factory. If you need to come in and take your own
VIM简易使用教程
Extension fragment
2022 gas examination question bank and online simulation examination
LM小型可编程控制器软件(基于CoDeSys)笔记二十:plc通过驱动器控制步进电机
Internet winter, how to spend three months to make a comeback
Registration of P cylinder filling examination in 2022 and analysis of P cylinder filling
pytorch 卷积操作
随机推荐
About the transmission pipeline of stage in spark
Obtain detailed ideas for ABCDEF questions of 2022 American Games
OdeInt與GPU
Grey correlation cases and codes
Basic exercise of test questions hexadecimal to decimal
The junior college students were angry for 32 days, four rounds of interviews, five hours of soul torture, and won Ali's offer with tears
TASK04|数理统计
Why is Internet thinking not suitable for AI products?
I also gave you the MySQL interview questions of Boda factory. If you need to come in and take your own
LM small programmable controller software (based on CoDeSys) note 20: PLC controls stepping motor through driver
测量三相永磁同步电机的交轴直轴电感
Caijing 365 stock internal reference | the first IPO of Beijing stock exchange; the subsidiary of the recommended securities firm for gambling and gambling, with a 40% discount
2022 gas examination question bank and online simulation examination
Matters behind the construction of paint testing laboratory
神经网络-最大池化的使用
Codeforces Round #771 (Div. 2) ABCD|E
Web server: how to choose a good web server these five aspects should be paid attention to
2022 t elevator repair new version test questions and t elevator repair simulation test question bank
JS rotation chart
Threejs opening