Search Insert Position

忘记了check 最后的情况是怎么check得,忘记考虑了target的位置要插在两端的情况

public class Solution{
	public int searchInsertPosition(int[] A, int target) {
      if (A == null ) {
          return -1;
      }
      
      if(A.length == 0){
          return 0;
      }

      int start = 0, end = A.length - 1;

      while(start + 1 < end){
        int mid = start + (end - start)/2;

        if (A[mid] == target) {
            return mid;
        }
        else if(A[mid] > target){
          end = mid;
        }else{
          start = mid;
        }
      }
      

      //the tricky thing here is to check the final condition, the target may less than A[start],l
      //larger than A[start] and less than A[end], or larger than A[end]
       if(target <= A[start]){
          return start;
      }
      
      if(target <= A[end]){
          return end;
      }
      
      else if (target > A[end]){
          return end+1;
      }

      return -1;
    }
}

Last updated