658. Find K Closest Elements

Information

  • Diffculty: Medium

  • Created: 2019-09-03 00:44:57

  • Last Motified: 2019-09-03 00:44:57

Solution

class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        m = min(arr, key=lambda i: abs(x - i))
        lo = arr.index(m)
        hi = lo + 1
        while hi - lo < k:
            if lo == 0:
                hi += 1
            elif hi == len(arr):
                lo -= 1
            elif abs(arr[lo - 1] - x) <= abs(arr[hi] - x):
                lo -= 1
            else:
                hi += 1
        return arr[lo:hi]