Leetcode 658. Find K Closest Elements
Given a sorted integer array arr
, two integers k
and x
, find the k
closest integers to x
in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
x
be outside the range of elements in arr
?
x
can be any integer, not necessarily within the range of elements in arr
.k
elements in arr
?
k
will always be valid, i.e., 1 <= k <= arr.length
.arr
?
Binary Search for Closest Element: Use binary search to locate the position in the array where x
would fit if inserted. This helps in finding the potential starting point for the closest elements.
k
closest elements:
left
and right
at this position.k
closest elements based on the absolute difference from x
.k
elements might be necessary, but since the array is already sorted, the selected window will also be sorted correctly.#include <vector>
#include <algorithm>
#include <cstdlib>
class Solution {
public:
std::vector<int> findClosestElements(std::vector<int>& arr, int k, int x) {
int left = 0;
int right = arr.size() - 1;
while (right - left >= k) {
if (abs(arr[left] - x) > abs(arr[right] - x)) {
left++;
} else {
right--;
}
}
return std::vector<int>(arr.begin() + left, arr.begin() + right + 1);
}
};
|arr[left] - x|
and |arr[right] - x|
.while
loop keeps shrinking the search window until its size is exactly k
. If the element at left
is less close to x
than the element at right
, increment left
; otherwise, decrement right
.arr[left]
to arr[right]
inclusive is returned as the result.while
loop runs in O(n - k)
operations, where n
is the size of the array.O(k)
.So, the overall time complexity is O(n - k + k) = O(n)
, but since we are performing the bulk of operations within the while
loop it’s more meaningful to consider the complexity as O(n - k)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?