使用二分搜索的思想,如果找到就返回当前位置,最后 low 肯定会 == high,再判断num[low] 是否 > target,则返回 low + 1,其余返回low
代码:
class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while(low < high){
int mid = (low + high) / 2;
if(nums[mid] == target)return mid;
if(nums[mid] < target)low = mid + 1;
if(nums[mid] > target)high = mid - 1;
}
if(nums[low] < target)return low + 1;
return low;
}
}



