作者:disappearedgod
时间:2014-9-10
题目
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
解法
代码
public class Solution {
public int searchInsert(int[] A, int target) {
int lo = -1;
int hi = A.length;
int mid = lo + (hi - lo)/2;
while(lo+1 != hi){
mid = lo + (hi - lo)/2;
if(A[mid] == target)
return mid;
else if(A[mid] > target){
if(mid > 1 && A[mid-1] < target)
return mid;
else if(mid == 0 )
return mid;
hi = mid;
}
else{
if( A.length > mid + 1 && A[mid+1] > target)
return mid+1;
else if(A.length == mid + 1)
return mid+1;
lo = mid;
}
}
return mid;
}
}
结果
Submit Time | Status | Run Time | Language |
---|---|---|---|
13 hours, 28 minutes ago | Accepted | 392 ms | java |