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