Python Solution


  • 0
    class Solution:
        def findClosestElements(self, arr, k, x):
            def binary_search(n):
                left, right = 0, len(arr) 
                while right - left > 1:
                    mid = (left + right) >> 1
                    if arr[mid] <= n:
                        left = mid
                    else:
                        right = mid
                return left
            idx1 = binary_search(x)
            left, right = idx1, idx1
            while right - left + 1 < k:
                if right == len(arr) -1 or (left > 0 and arr[right + 1] - x >= x - arr[left - 1]):
                    left -= 1
                else:
                    right += 1
            return arr[left : right + 1]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.