Search Insert Position

Search Insert Position

问题:

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.

思路:

二分查找问题

我的代码:

public class Solution {
    public int searchInsert(int[] A, int target) {
        if( A == null || A.length == 0) return -1;
        int left = 0;
        int right = A.length - 1;
        while(left <= right)
        {
            int mid = (left + right)/2;
            if(A[mid] == target)    return mid;
            else if(A[mid] > target)    right = mid - 1;
            else left = mid + 1;
        }
        return left;
    }
}
View Code

学习之处:

  • 二分查找left≤right
  • 二分查找停止循环时候的left和right的位置 想想真是公平哒,刚开始left < right,退出循环的话,left指向大的数据,right指向小的数据

if(null==nums || nums.length==0) return -1;
int left = 0;
int right = nums.length - 1;

while(left <= right){
int mid = (left+right)/2;
if(target == nums[mid]) return mid;
if(target > nums[mid]) left = mid+1;
if(target < nums[mid]) right = mid-1;
}

return left;

原文地址:https://www.cnblogs.com/sunshisonghit/p/4313581.html