Skip to content

Latest commit

 

History

History
31 lines (22 loc) · 559 Bytes

658.md

File metadata and controls

31 lines (22 loc) · 559 Bytes

658 Find K Closest Elements

Description

link


Solution

  • See Code

Code 2

O(log(n - k))

class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        left = 0
        right = len(arr) - k
        while left < right:
            mid = (right + left) // 2
            if x - arr[mid] > arr[mid + k] - x:
                left = mid + 1
            else:
                right = mid
        return arr[left:left + k]