Java AC 1
public class Solution { public int searchInsert(int[] A, int target) { if(A == null || A.length == 0){ return 0; } int len = A.length; if (target < A[0]) { return 0; } if (target > A[len-1]) { return len; } int low = 0; int high = len - 1; int mid = 0; while(low <= high){ mid = (low + high) >> 1; if(A[mid] > target){ high = mid - 1; }else if(A[mid] < target){ low = mid + 1; }else{ return mid; } } return low; } }Java AC 2 其实搜索过程应该是1要快些,但是LeetCode好像这个快了将近20ms,不应该呀。
public class Solution { public int searchInsert(int[] A, int target) { if(A == null || A.length == 0){ return 0; } int len = A.length; if (target < A[0]) { return 0; } if (target > A[len-1]) { return len; } int low = 0; int high = len - 1; int mid = 0; while(low <= high){ mid = (low + high) >> 1; if(A[mid] > target){ high--; }else if(A[mid] < target){ low++; }else{ break; } } return mid; } }