658. Find K Closest Elements (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class Solution(object):
    def findClosestElements(self, arr, k, x):
        """
        :type arr: List[int]
        :type k: int
        :type x: int
        :rtype: List[int]
        """
        # O(lgn + k)
        j = bisect.bisect(arr, x)
        i = j - 1
        m, n = k, len(arr)
        while m > 0:
            if i >= 0 and j < n:
                if x - arr[i] <= arr[j] - x:
                    i -= 1
                else:
                    j += 1
                m -= 1
            elif i < 0:
                return arr[ : k]
            else:
                return arr[-k : ]
        return arr[i + 1 : j]