> For the complete documentation index, see [llms.txt](https://suki.gitbook.io/91-days-algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/25.search-insert-position.md).

# 35. 搜索插入位置

<https://leetcode-cn.com/problems/search-insert-position/>

* [35. 搜索插入位置](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#35-搜索插入位置)
  * [题目描述](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#题目描述)
  * [方法 1：二分查找](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#方法-1二分查找)
    * [思路](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#思路)
    * [复杂度分析](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#复杂度分析)
    * [代码](https://suki.gitbook.io/91-days-algorithm/basic/two-pointers/pages/-MNWDoo5X0cWyh0BFebd#代码)

## 题目描述

```
给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 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

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
```

## 方法 1：二分查找

### 思路

用二分法找到目标值，或者找到大于目标值的数字中最左边的那个，返回下标。

### 复杂度分析

* 时间复杂度：$O(logN)$，N 是数组长度。
* 空间复杂度：$O(1)$。

### 代码

JavaScript Code

```javascript
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function (nums, target) {
    let l = 0,
        r = nums.length - 1,
        mid = 0;

    while (l <= r) {
        mid = ((r - l) / 2 + l) << 0;
        if (nums[mid] < target) l = mid + 1;
        else if (nums[mid] > target) r = mid - 1;
        else return mid;
    }

    return l;
};
```
