Bounded heap · Medium
A diagnostic picker chooses k recorded values nearest to a requested target. It must break equal-distance ties consistently and preserve duplicate occurrences. A small result should not require retaining a second full copy of the batch.
Return up to k values ordered by distance to target then value then original index using O(k) additional selection storage.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], target: integer, k: integer }
Fields
- nums is the measurement batch; target is the comparison value; k limits the number of returned entries.
Output
Return value
- Return values, not distances or indexes. Sort by absolute distance ascending, then numeric value ascending, then original index ascending.
- Duplicate entries remain separate. k = 0 returns []; k greater than n returns every entry in the required order.
Constraints
- 0 <= nums.length <= 100000; values are signed integers between -1000000000 and 1000000000.
- -1000000000 <= target <= 1000000000; 0 <= k <= 100001.
Examples
Example 1
{
"k": 3,
"nums": [
8,
2,
6,
4
],
"target": 5
}Returns
[
4,
6,
2
]Example 2
{
"k": 2,
"nums": [
2,
2,
3
],
"target": 2
}Returns
[
2,
2
]Required complexity
O(n log(k + 1) + k log(k + 1)) time and O(min(n,k) + 1) auxiliary space