Given a target number and an integer array A sorted in ascending order, find the index i
in A such that A[i] is closest to the given target.
Return -1 if there is no element in the array.
分析
使用binary Search 找到可以插入 target 的 position, 例如是 i, 那么,从i(包括i)到后面,都是大于等于target的数字
1 如果 i == 0, return i,因为A[i]一定是最接近 target的数字,后面的数字都大于A[i]
2 如果 i > =,那么需要考虑A[i] 和 A[i - 1] 哪个更接近 target,就返回哪一个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class Solution {
/**
* @param A an integer array sorted in ascending order
* @param target an integer
* @return an integer
*/
public int closestNumber( int [] A, int target) {
// Write your code here
if (A == null || A.length == 0 )
return - 1 ;
int left = 0 , right = A.length - 1 , mid;
while (left < right){
mid = left + (right - left) / 2 ;
if (A[mid] < target){
left = mid + 1 ;
}
else {
right = mid;
}
}
// when left == right, this is the first position that target can be insert
if (right > 0 && (A[right] - target) > (target - A[right - 1 ]))
return right - 1 ;
else
return right;
}
} |