# 搜索插入位置
<p>给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。</p><p>你可以假设数组中无重复元素。</p><p><strong>示例 1:</strong></p><pre><strong>输入:</strong> [1,3,5,6], 5<strong><br />输出:</strong> 2</pre><p><strong>示例&nbsp;2:</strong></p><pre><strong>输入:</strong> [1,3,5,6], 2<strong><br />输出:</strong> 1</pre><p><strong>示例 3:</strong></p><pre><strong>输入:</strong> [1,3,5,6], 7<strong><br />输出:</strong> 4</pre><p><strong>示例 4:</strong></p><pre><strong>输入:</strong> [1,3,5,6], 0<strong><br />输出:</strong> 0</pre>
<p>以下错误的选项是？</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
    Solution sol;
    int res;
    vector<int> nums{1, 3, 5, 6};
    int target = 5;

    res = sol.searchInsert(nums, target);

    cout << res;
    return 0;
}
```

## 答案
```cpp
class Solution
{
public:
    int searchInsert(vector<int> &nums, int target)
    {

        int len = nums.size();
        if (target <= nums[0])
            return 0;

        for (int i = 0; i < len; i++)
        {
            if (nums[i] == target)
                return i - 1;
            else if (target < nums[i])
                return i + 1;
        }

        return len;
    }
};
```
## 选项

### A
```cpp
class Solution
{
public:
    int searchInsert(vector<int> &nums, int target)
    {
        int lo = -1;
        int hi = nums.size();
        while (lo + 1 < hi)
        {
            int mid = lo + (hi - lo) / 2;
            if (target > nums[mid])
            {
                lo = mid;
            }
            else
            {
                hi = mid;
            }
        }
        return hi;
    }
};
```

### B
```cpp
class Solution
{
public:
    int searchInsert(vector<int> &nums, int target)
    {
        int len = nums.size();
        if (len == 0)
            return 0;
        for (int i = 0; i < len; i++)
        {
            if (nums[i] >= target)
                return i;
        }
        return len;
    }
};
```

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