思路:其实就是用普通的二分查找,只不过在找不到该数时,left下标就是应该插入的位置,返回该下标即可。
Java代码如下:
public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = (left + right)/2; if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return left; }