Find K Closest Elements
Given a sorted array, two integersk
andx
, find thek
closest elements tox
in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Example 2:
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 10^4
Absolute value of elements in the array and x will not exceed 10^4
UPDATE (2017/9/19): Thearrparameter had been changed to an array of integers(instead of a list of integers).Please reload the code definition to get the latest changes.
Analysis
This is probably one of my favorite binary search problem.
Intuitively, one would find the element x
in the array first, and then use two pointers or something else to find the k
closest neighbors around the x
. However, this problem has a much more elegant approach, which is just using binary search itself.
It's hard to think at first about modifying the condition statements in the binary search, though, without deep understanding of how binary search works.
Instead of finding x
position, we can find the left boundary index of the k
elements closest to x
.
Therefore the condition becomes:
And since we prefer the smaller indexes, we exclude the "="
equal in the comparison, thus we move left when the x - arr[mid] = arr[mid+k] - x
, to make sure we prioritize the smaller indexes when there's a tie.
Another thing to be careful is setting the initial left and right boundaries (indexes), since we will use arr[mid + k]
, thus, we need to make sure the starting right boundaries is less than arr.length - k
to avoid index out of bound error.
这题最妙的地方在于
搜索k个距离(数组元素之差的绝对值,而不是下标的距离)最近的数中最小的那个下标,这样通过k就可知道右边界的位置
改变binary search中的条件判断语句,改为k个元素中最小值与最大值与x元素的距离绝对值大小的比较
x - arr[mid] vs arr[mid+k] - x
left, right初始值的设定,因为需要
[mid + k]
,所以right的初始值需要(从arr.length - 1
)缩小至arr.length - k - 1
以防止数组下标越界 (根据Template #1,#3,如果是Template #2 则需从arr.length
改为arr.length - k
)
Solution
BS Template #1
BS Template #2
Reference Solution with comment from LeetCode @meganlee
Reference
Last updated