题目描述:
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 1:
Input: [1,3,5,6], 0 Output: 0
由于是排序数组,所以采用二分搜索,如果能查找到直接返回下标,如果不能查找到,则需要返回第一个比它大的元素的下标(即插入的位置)。对于二分查找,如果查找不到的话,begin指针的最终位置恰好满足题意,所以进行二分查找之后,直接返回begin指针即可。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.size()==0) return 0;
int begin=0;
int end=nums.size()-1;
while(begin<=end)
{
int mid=(begin+end)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) begin=mid+1;
else if(nums[mid]>target) end=mid-1;
}
return begin;
}
};