Loading...
Loading...
You are given a list of points points and an integer k. Each element in points contains [x, y] meaning there's a point at the integer coordinates (x, y).
The distance between two points [x1, y1] and [x2, y2] is the smaller of their horizontal gap and their vertical gap: min(abs(x1 - x2), abs(y1 - y2)).
For every pair of indices i < j, write down the distance between points[i] and points[j]. With n points, that gives n * (n - 1) / 2 values.
Return the k-th smallest of these values, counting from 1.
Each pair counts separately, so a value shared by several pairs takes several places in the sorted order. points may contain the same point more than once. Two equal points are at distance 0.
Input: points = [[0, 0],
[3, 1],
[1, 5],
[4, 4]]
k = 1
Output: 1
Explanation: The six pairs and their distances are:
[0,0] and [3,1]: min(3, 1) = 1
[0,0] and [1,5]: min(1, 5) = 1
[0,0] and [4,4]: min(4, 4) = 4
[3,1] and [1,5]: min(2, 4) = 2
[3,1] and [4,4]: min(1, 3) = 1
[1,5] and [4,4]: min(3, 1) = 1
Sorted, the distances are [1, 1, 1, 1, 2, 4]. The smallest is 1.
Input: points = [[0, 0],
[3, 1],
[1, 5],
[4, 4]]
k = 4
Output: 1
Explanation: The sorted distances are [1, 1, 1, 1, 2, 4]. Four different pairs have distance 1, so the 4th smallest value is still 1.
Input: points = [[0, 0],
[3, 1],
[1, 5],
[4, 4]]
k = 6
Output: 4
Explanation: k = 6 asks for the largest of the six distances. It belongs to [0,0] and [4,4], whose horizontal and vertical gaps are both 4.
Input: points = [[2, 7],
[2, 7],
[5, 1]]
k = 2
Output: 3
Explanation: The two copies of [2,7] are at distance 0. Each copy is at distance min(3, 6) = 3 from [5,1]. The sorted distances are [0, 3, 3], so the 2nd smallest is 3.
points.length ≤2⋅104points[i].length == 2x, y ≤109k ≤ n * (n - 1) / 2, where n is points.length