Skip to main content

658 - Find K Closest Elements

Details

KeyValue
Linkhttps://leetcode.com/problems/find-k-closest-elements/submissions/
LanguagePython 3
Runtime602 ms, faster than 39.84% of Python3 online submissions for Find K Closest Elements
Memory Usage15.6 MB, less than 45.71% of Python3 online submissions for Find K Closest Elements
DatastructuresList[int]
AlgorithmsBinary Search
ComplexityTime: O(log(N-K) Memory: O(C)

Procedure

  1. ...

Code

class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left, right = 0, len(arr) - k

while left < right:
mid = (left + right) // 2
if x > (arr[mid] + arr[mid+k]) // 2:
left = mid + 1
else:
right = mid

return arr[left:left+k]