Closest number in Sorted Array
Given a target number and an integer array a sorted in ascending order, find the index in i
a such that a[i] is closes T 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 duplicate elements in the array, and we can return any of the indices with same value.
1 classSolution {2 Public: 3 /** 4 * @param A integer array sorted in ascending order 5 * @param target an integer 6 * @return A Integer 7*/ 8 intClosestnumber (vector<int>& A,inttarget) { 9 if(a.size () = =0) {Ten return-1; One } A - intb =0, E = A.size ()-1; - while(b +1<e) { the intMid = B + (e-b)/2; - if(A[mid] = =target) { - returnmid; -}Else if(A[mid] <target) { +b =mid; -}Else { +E =mid; A } at } - if(ABS (A[b]-target) < ABS (A[e]-target)) { - returnb; -}Else { - returne; - } in } -};
Closet number in sorted array