- Closest Number in Sorted Array
中文English
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.
Example
Example 1:
Input: [1, 2, 3] , target = 2
Output: 1.
Example 2:
Input: [1, 4, 6], target = 3
Output: 1.
Example 3:
Input: [1, 4, 6], target = 5,
Output: 1 or 2.
Challenge
O(logn) time complexity.
Notice
There can be duplicate elements in the array, and we can return any of the indices with same value.
解法1:二分法。
代码如下:
class Solution {
public:
/**
* @param A: an integer array sorted in ascending order
* @param target: An integer
* @return: an integer
*/
int closestNumber(vector<int> &A, int target) {
int n = A.size();
if (n == 0) return 0;
if (n == 1) return A[0];
int start = 0, end = n - 1;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] < target) {
start = mid;
} else if (A[mid] > target) {
end = mid;
} else {
return mid;
}
}
if (abs(target - A[start]) < abs(target - A[end])) {
return start;
} else {
return end;
}
}
};