# 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector nums{1, 3, 5, 6};
int target = 5;
res = sol.searchInsert(nums, target);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int searchInsert(vector &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 &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 &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 &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;
}
};
```