题目让找出target存在的位置,如果不存在,找出合适的插入位置。这道题属于典型的二分查找题,唯一的区别在于没找到的情况不是返回-1,而是返回left
代码如下
循环法
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 middle=(left+right)/2;
if(A[middle]==target)
return middle;
if(A[middle]>target)
right=middle-1;
else
left=middle+1;
}
return left;
}
递归法
public int searchInsert(int[] A, int target) {
if (A == null || A.length == 0)
return -1;
return searchInsert(A, 0, A.length - 1, target);
}
public int searchInsert(int[] A, int left, int right, int target) {
if (left > right)
return left;
int middle = (left + right) / 2;
if (A[middle] == target)
return middle;
if (A[middle] > target)
return searchInsert(A, left, middle - 1, target);
else
return searchInsert(A, middle + 1, right, target);
}