问题描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
求解
经典的“二分查找”在未找到匹配值时,一般返回 -1,这里在经典算法上稍加改造便能符合题目需求
class Solution
{
public:
int searchInsert(vector<int> &A, int target)
{
int left = 0;
int right = A.size() - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (target < A[mid])
{
right = mid - 1;
}
else if (A[mid] < target)
{
left = mid + 1;
}
else
{
return mid;
}
}
return left;
}
};
我们还有STL这个“外挂”,只需一行代码就能解决问题
class Solution2
{
public:
int searchInsert(vector<int> &A, int target)
{
return lower_bound(A.begin(), A.end(), target) - A.begin();
}
};