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.
Here
are few examples.[1,3,5,6]
,
5 → 2[1,3,5,6]
,
2 → 1[1,3,5,6]
,
7 → 4[1,3,5,6]
,
0 → 0
1 public class Solution { 2 public int searchInsert(int[] A, int target) { 3 int end = A.length-1; 4 int start = 0; 5 while(start<=end){ 6 int mid =(start+end)/2; 7 if(A[mid]==target) return mid; 8 else if( mid>0 && A[mid-1]<target && A[mid]>target) return mid; 9 else if(A[mid]>target) end = mid-1; 10 else start = mid+1; 11 } 12 return start; 13 } 14 }
原文:http://www.cnblogs.com/krunning/p/3540027.html