image.png

解题思路

二分查找

image.png

  1. public int searchInsert(int[] nums, int target) {
  2. int left = 0, right = nums.length - 1;
  3. while (left <= right) {
  4. int mid = (left + right) / 2;
  5. if(nums[mid] == target) {
  6. return mid;
  7. }else if(nums[mid] < target) {
  8. left = mid + 1;
  9. } else {
  10. right = mid - 1;
  11. }
  12. }
  13. return left;
  14. }