# 35. Search Insert Position (Easy)

## 1.問題&#x20;

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHNyFauUzaYrzRH1JVh%2F-LHNyz23PAYnG0Bv2mb0%2F2018071408.jpg?alt=media\&token=935dab40-1cad-4529-9ee8-22db00de9b28)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHNyFauUzaYrzRH1JVh%2F-LHNymCXu4AfXD_Q8iX4%2F2018071407.jpg?alt=media\&token=6f9a74c6-50fe-4ee7-bd98-1a1ce6b0a386)

