658. Find K Closest Elements
Last updated
Was this helpful?
Last updated
Was this helpful?
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
Thoughts:
Binary -searching the first index i that arr[i] is closer or equally close to arr[i+k] (Original )
Binary-searching forx
and then expanding to the left and to the right: The idea is to find the first number which is equal to or greater thanx
inarr
. Then, we determine the indices of the start and the end of a subarray inarr
, where the subarray is our result. The time complexity is O(logn + k)
.
Code: Binary -searching for the first index i T: O(log(n-k))
Python: T: O(log(n-k))
Code 2: T: O(log(n)+k)