Problem · Array
K Closest Points to a Target
Learn this problemProblem statement
Given distinct two-dimensional integer points, a two-dimensional integer target, and an integer k, return the k points closest to target.
For a point [x, y], use squared Euclidean distance (x - target[0])^2 + (y - target[1])^2. Smaller distance is closer. Break equal-distance ties by smaller x, then smaller y.
Return the selected points ordered from closest to farthest using that same distance-and-coordinate order.
Function
kClosestPoints(points: int[][], target: int[], k: int) → int[][]Examples
Example 1
points = [[1,3],[-2,2],[2,-2],[4,0]]target = [0,0]k = 2return = [[-2,2],[2,-2]]The two selected points both have squared distance 8. The tie is resolved by the smaller x-coordinate.
Example 2
points = [[5,5],[3,4],[4,3],[2,2]]target = [3,3]k = 3return = [[3,4],[4,3],[2,2]]The first two returned points have squared distance 1. [2,2] follows with squared distance 2.
Example 3
points = [[0,0]]target = [7,-4]k = 1return = [[0,0]]The only point must be returned.
Constraints
1 <= points.length <= 10^5.points[i].length == 2andtarget.length == 2.- All points are distinct.
1 <= k <= points.length.-10^9 <= points[i][j], target[j] <= 10^9.- Use 64-bit arithmetic for squared distances.