Given an array of numeric distances distances, where each value represents the distance of one candidate vector from a query vector, return the indices of the k nearest neighbors in ascending order of distance. If two distances are equal, return the smaller index first. Write an optimized algorithm without using external libraries.
Example 1:
Input: distances = [0.42, 0.15, 0.33, 0.15], k = 2
Output: [1, 3]
Explanation: The two smallest distances are 0.15 at indices 1 and 3.
Example 2:
Input: distances = [1.2, 0.9, 2.5, 0.4], k = 3
Output: [3, 1, 0]
Explanation: Sorted by distance, the nearest indices are 3, 1, and 0.
1 <= len(distances) <= 10^50 <= distances[i] <= 10^91 <= k <= len(distances)Given an array of numeric distances distances, where each value represents the distance of one candidate vector from a query vector, return the indices of the k nearest neighbors in ascending order of distance. If two distances are equal, return the smaller index first. Write an optimized algorithm without using external libraries.
Example 1:
Input: distances = [0.42, 0.15, 0.33, 0.15], k = 2
Output: [1, 3]
Explanation: The two smallest distances are 0.15 at indices 1 and 3.
Example 2:
Input: distances = [1.2, 0.9, 2.5, 0.4], k = 3
Output: [3, 1, 0]
Explanation: Sorted by distance, the nearest indices are 3, 1, and 0.
1 <= len(distances) <= 10^50 <= distances[i] <= 10^91 <= k <= len(distances)