658. Find K Closest Elements
Description
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|
, or
|a - x| == |b - x| and a < b
Thoughts
-
A Straight-forward Binary Search Solution
We can use binary search template to find the first number which is larger or equals to x, (say pivot).
Then from pivot position and pivot - 1, we use the 2-pointers to find the closest numbers until we find k numbers.- Time complexity: O(logn): find the pivot + O(k):find the k numbers + O(klogk): sort the result array
- Space complexity: O(k) for result array
-
Binary Search to find the left bound of the k window.
The answer should be a k-length window. To get the k-length window we only need to find the start position (left bound of the k- window).
We can use binary search to find the left bound. But we need to know how to define if the mid number is the start position or not.
Think it this way: from position mid, we look at the k numbers after mid. So it’s arr[mid: mid + k + 1]. This window has k + 1 numbers in it. And either mid or mid + k is the one that we need to delete.- If x - arr[mid] > arr[mid + k] - x ⇒ for sure arr[mid] is not in the k numbers and all the numbers before mid should not be the start.
- If x - arr[mid] <= arr[mid + k] - x ⇒ for sure arr[mid + k] is not in the k numbers and all the numbers after mid + k should not be the result. The left bound should be mid or someone before mid.
- Time complexity: O(logn): find the left bound + O(k):find the k numbers
- Space complexity: O(k) for result array
Code
leverage a regular binary search template
def findClosestElements(self, arr: List[int]