LeetCode 35. 搜索插入位置

35. 搜索插入位置

解题思路

二分查找模板

参考代码

闭区间写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int searchInsert(int[] nums, int target) {
return solutionV1(nums, target);
// return solutionV2(nums, target);
}

private int solutionV1(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}

private int solutionV2(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
}

LeetCode 35. 搜索插入位置
https://sowink.cn/2026/02/08/LeetCode-35-搜索插入位置/
作者
Xurx
发布于
2026年2月8日
许可协议