Given a target number, a non-negative integer and an k
integer array A sorted in ascending order, find the K C Losest numbers to target in A, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same.
Example
Given A = [1, 2, 3]
, target = and 2
k = 3
, return [2, 1, 3]
.
Given A = [1, 4, 6, 8]
, target = and 3
k = 3
, return [4, 1, 6]
.
Locate the first index that is greater than or equal to target, and find the index that matches the criteria near index.
Don't put Target + + as a hassle.
1 Public classSolution {2 /**3 * @paramA Integer Array4 * @paramTarget an integer5 * @paramk a non-negative integer6 * @returnAn integer array7 */8 Public int[] Kclosestnumbers (int[] A,intTargetintk) {9 if(A = =NULL|| A.length = = 0) {Ten returnA; One } A if(k >a.length) { - returnA; - } the - int[] result =New int[K]; - intindex =FindIndex (A, target); - intbegin = Index-1, end =index; + for(inti = 0; I < K; i++) { - if(Begin < 0) { +Result[i] = a[end++]; A}Else if(End >=a.length) { atResult[i] = a[begin--]; -}Else { - if(Math.Abs (Target-a[begin]) <= Math.Abs (A[end]-target)) { -Result[i] = a[begin--]; -}Else { -Result[i] = a[end++]; in } - } to } + returnresult; - } the * //Find first position which GE target if connot find return a.length-1 $ Private intFindIndex (int[] A,inttarget) {Panax Notoginseng intleft = 0, right = a.length-1; - while(Left + 1 <Right ) { the intMid = left + (right-left)/2; + if(A[mid] = =target) { Aright =mid; the}Else if(A[mid] <target) { +left =mid; -}Else { $right =mid; $ } - } - if(A[left] >=target) { the returnLeft ; - }Wuyi if(A[right] >=target) { the returnRight ; - } Wu returnA.length-1; - } About}
K Closest Numbers in Sorted Array