Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume NO duplicates in the array.
Note: The number you are looking for is larger than the number in the array, so the inserted position is a.length.
1 Public classSolution {2 /** 3 * param a:an integer sorted array4 * param target:an integer to be inserted5 * Return:an integer6 */7 Public intSearchinsert (int[] A,inttarget) {8 if(A = =NULL|| A.length = = 0) {9 return0;Ten } One intBegin = 0; A intEnd = A.length-1; - while(Begin + 1 <end) { - intMID = begin + (End-begin)/2; the if(A[mid] = =target) { - returnmid; - } - if(A[mid] >target) { +End =mid; -}Else { +Begin =mid; A } at } - if(A[begin] >=target) { - returnbegin; -}Else if(A[end] >=target) { - returnend; -}Else { in returnEnd + 1; - } to } +}
Search Insert Position