classSolution: deffindClosestElements(self, arr, k, x): result = [] index = self.binarySearch(arr, x) left = index right = index + 1 length = len(arr) while k: if left < 0: result = result + [arr[right]] right += 1 elif right >= length: result = [arr[left]] + result left -= 1 elif x - arr[left] <= arr[right] - x: result = [arr[left]] + result left -= 1 else: result = result + [arr[right]] right += 1 k -= 1 return result
defbinarySearch(self, arr, x): left = 0 right = len(arr) - 1 index = 0 while left <= right: middle = (left + right) // 2 if arr[middle] < x: index = left left += 1 elif arr[middle] > x: right -=1 index = right else: return middle return index
Version 2
1 2 3 4 5 6 7 8 9 10 11
classSolution: deffindClosestElements(self, arr, k, x): left = 0 right = len(arr) - k while left < right: middle = (left + right) // 2 if x - arr[middle] > arr[middle + k] - x: left = middle + 1 else: right = middle return arr[left:left+k]