# 35. Search Insert Position (Easy)

## 1.問題&#x20;

* 給予一個sorted list以及target value, 回傳在陣列的位置或是他應該插入的位置

![](/files/-LHNyz23PAYnG0Bv2mb0)

## 2.想法&#x20;

* Binary search

## 3.程式碼&#x20;

```
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int start = 0, end = nums.size()-1;
        if (nums[end] < target) {
            return end + 1;
        }
        if (nums[start] > target) {
            return start;
        }
        while (start <= end) {
            int mid = start + (end - start) /2;
            if (nums[mid] == target ||
                (nums[mid] > target && nums[mid - 1] < target)) {
                return mid;
            }
            if (nums[mid] < target && nums[mid + 1] > target) {
                return mid + 1;
            }
            if (nums[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
    }
};
```

## 4.Performance

![](/files/-LHNymCXu4AfXD_Q8iX4)


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/35.-search-insert-position-easy.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.
