The Find K Closest Elements problem involves finding the K
closest elements to a given target in a sorted array. The result should also be sorted in ascending order.
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int left = 0, right = arr.length - k;
while (left < right) {
int mid = left + (right - left) / 2;
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1; // Narrow down to the right half
} else {
right = mid; // Narrow down to the left half
}
}
List<Integer> result = new ArrayList<>();
for (int i = left; i < left + k; i++) {
result.add(arr[i]);
}
return result;
}
}
O(log(N - K))
โ Halving the search space for the starting index.O(K)
โ Adding K elements to the result list.O(log(N - K) + K)
.Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Explanation:
- The 4 closest elements to 3 are [1, 2, 3, 4].