Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
思路:
用二分搜索,当mid对应的数据与target相等时,说明存在,直接返回mid;关键是当数组中没有等于target的数据时,怎么处理?其实二分搜索如果找不到target时,最后的状态是right指向第一个小于target的数,left指向第一个大于target的数,此时返回left即可。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
int mid = 0;
while(left <= right)
{
mid = (left+right)/2;
if(target > nums[mid])
{
left = mid+1;
}
else if(target < nums[mid])
{
right = mid-1;
}
else
{
return mid;
}
}
return left;
}
};