python | binary-search | two pointers | two solutions | O(n)
two pointers method:\n\n\nclass Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        # find the closest number\n 
two pointers method:\n\n```\nclass Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        # find the closest number\n        right = self.getClosetNumber(arr, x)\n        left = right - 1\n        \n        # get the pointers array\n        for _ in range(k):\n            if self.getLeftCloserNumber(arr, left, right, x) == right:\n                right += 1\n            else:\n                left -= 1\n        left = 0 if right - k < 0 else right - k\n        print(left, right)\n        return arr[left:] if left == right else arr[left:right]\n            \n        \n        \n    def getClosetNumber(self, nums, target):\n        left, right = 0, len(nums) - 1\n        \n        while left + 1 < right:\n            mid = (left + right) // 2\n            if nums[mid] < target:\n                left = mid\n            else:\n                right = mid\n        \n        return self.getLeftCloserNumber(nums, left, right, target)\n    \n    def getLeftCloserNumber(self, nums, left, right, target):\n        if left < 0:\n            return right\n        if right > len(nums) - 1:\n            return left\n        return left if abs(nums[left] - target) <= abs(nums[right] - target) else right\n```\nbinary search:\n```\nclass Solution:\n    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n        # use two mid pointes method\n        left, right = 0, len(arr) - k\n        \n        while left < right:\n            mid = (left + right) // 2\n            # mid + k must not out of range\n            if abs(arr[mid] - x) > abs(arr[mid + k]  - x):\n                left = mid + 1\n            # if All duplicate and the first one is large than x\n            # arr[mid] < x need to filter out this kind of case: [1,1,2,2,2,2,2,2,2,2] 3 1\n            elif arr[mid] == arr[mid + k] and arr[mid] < x:\n                left = mid + 1\n            else:\n                right = mid\n            \n        return arr[left: left + k]\n```
['Two Pointers', 'Binary Tree', 'Python', 'Python3']