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对应的值相等,则会返回mid;若不相等,且没有找到相等的值,则会退出循环,退出循环后mid指向的元素两侧即为新元素需要插入的位置,此时 具体要查到左边还是右边,需要与插入的元素做比较。
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0||nums[0]>target) return 0;
if(nums[nums.length-1]<target) return nums.length;
int low=0;
int high=nums.length-1;
int mid=0;
while(low<=high){
mid=(low+high)/2;
if(nums[mid]<target){
low=mid+1;
}else if(nums[mid]>target){
high=mid-1;
}else{
return mid;
}
}
return nums[mid]>target?mid:mid+1;
}
}