Given a target integer T, a non-negative integer K and an integer array A sorted in ascending order, find the K closest numbers to T in A. If there is a tie, the smaller elements are always preferred.
Assumptions
- A is not null
- K is guranteed to be >= 0 and K is guranteed to be <= A.length
Return
- A size K integer array containing the K closest numbers(not indices) in A, sorted in ascending order by the difference between the number and T.
Examples
- A = {1, 2, 3}, T = 2, K = 3, return {2, 1, 3} or {2, 3, 1}
- A = {1, 4, 6, 8}, T = 3, K = 3, return {4, 1, 6}
def kClosest(self, array, target, k):
if not array:
return -1
left=0
right=len(array)-1
ans=[]
while right - left + 1 > k:
if abs(array[left] - target) > abs(array[right] - target):
left += 1
else:
right -= 1
return sorted(array[left:right + 1], key=lambda x: abs(x - target))