algorithm-base/animation-simulation/二分查找及其变种/leetcode35搜索插入位置.md

72 lines
2.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [35. ](https://leetcode-cn.com/problems/search-insert-position/)
####
>
>
>
1:
> : [1,3,5,6], 5
> : 2
2:
> : [1,3,5,6], 2
> : 1
3:
> : [1,3,5,6], 7
> : 4
4:
> : [1,3,5,6], 0
> : 0
####
left
![](https://img-blog.csdnimg.cn/img_convert/d806cb5199c4baeebc62bebe29d7eded.gif)
####
Java Code:
```java
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length-1;
//注意循环条件
while (left <= right) {
//求mid
int mid = left + ((right - left ) >> 1);
//查询成功
if (target == nums[mid]) {
return mid;
//右区间
} else if (nums[mid] < target) {
left = mid + 1;
//左区间
} else if (nums[mid] > target) {
right = mid - 1;
}
}
//返回插入位置
return left;
}
}
```
Go Code: