题意:

image.png

解题思路:

  1. 思路:二分查找,
  2. 1. 如果存在,则必然有值,返回对应下标即可;
  3. 2. 如果不存在则返回顺序插入的位置;
  4. 2.1 通过二分每次排除一半的数字,如果目标值小于中间值,则肯定在中间值左侧,反之在右侧;
  5. 2.2 直到low > high 最终返回low

PHP代码实现:

  1. class Solution {
  2. function searchInsert($nums, $target) {
  3. if ($nums == null) return -1;
  4. $low = 0;
  5. $high = count($nums) - 1;
  6. while ($low <= $high) {
  7. $mid = $low + floor(($high - $low) / 2);
  8. if ($target < $nums[$mid]) {
  9. $high = $mid - 1;
  10. } else if ($target > $nums[$mid]) {
  11. $low = $mid + 1;
  12. } else {
  13. return $mid;
  14. }
  15. }
  16. return $low;
  17. }
  18. }

GO代码实现:

  1. func searchInsert(nums []int, target int) int {
  2. left :=0
  3. right := len(nums) - 1
  4. mid := 0
  5. for left <= right {
  6. mid = (left + right) / 2
  7. if nums[mid] == target {
  8. return mid
  9. } else if nums[mid] > target {
  10. right = mid - 1
  11. } else {
  12. left = mid + 1
  13. }
  14. }
  15. return left
  16. }