![]() |
VOOZH | about |
You are given a sorted array arr[] containing unique integers, a number k, and a target value x. Your goal is to return exactly k elements from the array that are closest to x, excluding x itself if it is present in the array.
An element a is closer to x than b if:
|a - x| < |b - x|, or|a - x| == |b - x| and a > b (i.e., prefer the larger element if tied)Examples:
Input: arr[] = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56], k = 4, x = 35
Output: 39 30 42 45
Explanation: First closest element to 35 is 39.
Second closest element to 35 is 30.
Third closest element to 35 is 42.
And fourth closest element to 35 is 45.Input: arr[] = [1, 3, 4, 10, 12], k = 2, x = 4
Output: 3 1
Explanation:4is excluded, Closest elements to4are:3 (1),1 (3). So, the 2 closest elements are:3 1
Table of Content
The idea is to use the absolute difference between each element and the target value to measure how close they are. Then, we apply custom sorting: elements with smaller differences come first, and in case of a tie, the larger element is preferred. we take the k element from get from custrom sorted array then return it.
39 30 42 45
The idea is to first go through the array to find the last element that is less than or equal to the target value, skipping the target if it's present. Then, we use two pointers to choose the k closest elements by comparing their differences, while following the tie-breaking rules.
39 30 42 45
The idea is to first use binary search to quickly find the last element in the array that is less than or equal to the target (skipping the target itself if it exists). Then, we use a two-pointer approach to select the k closest elements, following the tie-breaking rules.
39 30 42 45