35. 搜索插入位置

题目链接 https://leetcode-cn.com/problems/search-insert-position/
除了二分法外,还可以遍历全部,找不到即输出数组长度的值,也就是插入未知的下标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
int right = nums.size()-1; //注意边界
int left = 0;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target > nums[mid] ) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
};

35. 搜索插入位置
https://pisces34.github.io/2021/05/13/leetcode/search-insert/
发布于
2021年5月13日
许可协议