Closest Number in Sorted Array
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
Given [1, 2, 3]
and target = 2
, return 1
.
Given [1, 4, 6]
and target = 3
, return 1
.
Given [1, 4, 6]
and target = 5
, return 1
or 2
.
Given [1, 3, 3, 4]
and target = 2
, return 0
or 1
or 2
.
Note
There can be duplicate elements in the array, and we can return any of the indices with same value.
1 class Solution { 2 public: 3 /** 4 * @param A an integer array sorted in ascending order 5 * @param target an integer 6 * @return an integer 7 */ 8 int closestNumber(vector<int>& A, int target) { 9 if (A.size() == 0) { 10 return -1; 11 } 12 13 int b = 0, e = A.size() - 1; 14 while (b + 1 < e) { 15 int mid = b + (e - b) / 2; 16 if (A[mid] == target) { 17 return mid; 18 } else if (A[mid] < target) { 19 b = mid; 20 } else { 21 e = mid; 22 } 23 } 24 if (abs(A[b] - target) < abs(A[e] - target)) { 25 return b; 26 } else { 27 return e; 28 } 29 } 30 };
时间: 2024-12-06 17:53:49