# 19. 搜索插入位置

python

```python
class Solution:
    def searchInsert(self, A, targ):
        start = 0
        end = len(A) - 1
        # 不+1可能死循环
        while start + 1 < end:
            mid = int((start + end) / 2)
            if A[mid] == targ:
                return mid
            elif A[mid] < targ:
                start = mid
            else:
                end = mid
        # 此时已经确定不存在A里面了
        if A[start] > targ:  # 比start小
            return start
        elif A[end] > targ:  # 比end小
            return end
        else:
            return len(A)  # 比end大


s = Solution()
print(s.searchInsert([1, 3, 5, 6], 5))
print(s.searchInsert([1, 3, 5, 6], 2))
print(s.searchInsert([1, 3, 5, 6], 7))
print(s.searchInsert([1, 3, 5, 6], 0))
```

java

```java
/**
 * 搜索插入位置.
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 *
 * 你可以假设数组中无重复元素。
 *
 * 示例 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
 */
public class Solution35 {

    public int searchInsert(int[] nums, int target) {
        return binSearch(nums,0,nums.length-1,target);
    }

    /**
     * 二分查找
     * @param nums 数组
     * @param low 低位
     * @param high 高位
     * @param value 待查找值
     * @return 位置，未找到返回low
     */
    public int binSearch(int[] nums,int low,int high,int value){
        int middle=low+(high-low)/2;
        if(low>high) return low;
        if(value==nums[middle]) return middle;
        else if(value<nums[middle]) return binSearch(nums,low,middle-1,value);
        else return binSearch(nums,middle+1,high,value);
    }

    public static void main(String[] args) {
        int[] nums = {
                1, 3, 5, 6
        };
        int target = 0;
        int r = new Solution35().searchInsert(nums, target);
        System.out.println(r);
    }
}
```


---

# 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://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/sou-suo-cha-zhao-lei/19-sou-suo-cha-ru-wei-zhi.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.
