classSolution:deffindClosestElements(self,arr: List[int],k:int,x:int) -> List[int]: n =len(arr)# 二分法确定`x`在数组中的位置 left, right =0, n -1while left <= right: mid = (left + right) //2if arr[mid]< x: left = mid +1else: right = mid -1# `left`为插入点, 判断`left`和`left - 1`两个位置哪个与`x`更相近# 以更相近的位置为中心位置, 向两侧扩展 center = (left -1) if left == n or (left >0and (x - arr[left -1]) <= (arr[left]- x)) else left left = right = center count =1while count < k:if left ==0: right +=1 count +=1elif right == n -1: left -=1 count +=1else:if (x - arr[left -1]) <= (arr[right +1]- x): left -=1else: right +=1 count +=1return arr[left: right +1]