# Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.\
`[1,3,5,6]`, 5 → 2\
`[1,3,5,6]`, 2 → 1\
`[1,3,5,6]`, 7 → 4\
`[1,3,5,6]`, 0 → 0

本题是基本考察二分查找的题目，与基本二分查找方法不同的地方是，二分查找法当查找的target不在list中存在时返回-1，而本题则需要返回该target应在此list中插入的位置。

当循环结束时，如果没有找到target，那么**left一定停target应该插入的位置上**，right一定停在恰好比target小的index上。

![](/files/-LrHZi5P350GyLddaV9M)

![](/files/-LrHZi5RGOZrGp_hZJHk)

O(logn)，空间复杂度O(1)

```
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left = 0
        right = len(nums)-1
        while left <= right:
            mid = (left + right)/2
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid-1
            else:
                left = mid+1
        return left
```

## 二刷：

用了九章模版：最后判断了三种情况，

1. target在start左边或者等于start， 返回start
2. taget在start和end 中间或者等于end，返回end
3. target在end外面，返回总长度

```
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        start, end = 0, len(nums)-1
        while start + 1 < end:
            mid = (start+end)/2
            if nums[mid] < target:
                start = mid
            else:
                end = mid

        if nums[start] >= target:
            return start
        elif nums[end] >= target:
            return end
        return len(nums)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://rachel2011.gitbook.io/leetcode_cc150/leetcode/search-insert-position.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
