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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1;
int mid;
while(lo <= hi){//用小于等于保证了对于单个元素数组也会进行比较
mid = lo + (hi-lo)/2;//mid的这样计算可以保证边界值不出错,因为int为向下取整
if(target > nums[mid]) lo = mid + 1;
else if(target < nums[mid]) hi = mid - 1;
else return mid;
}
return lo;//虽然是lo,但其实是返回的比target小的那个数值的下标值+1,注意,不能用hi,因为可能会变成-1
}
}