973. K Closest Points to Origin
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
Example 1
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)
Note
- 1 <= K <= points.length <= 10000
- -10000 < points[i][0] < 10000
- -10000 < points[i][1] < 10000
题意:在二维平面上, 给了一群点, 要求返回离原点最近的前 k 个点。 注意点之间的距离是用 Euclidean distance 来表示的。 这道题也可以用 heap 来解决。 组建一个 k 大小的 heap, 便可以在 nlogk 时间求出最结果。
代码 1
class Solution {
public int[][] kClosest(int[][] points, int K) {
PriorityQueue<Pair> pq = new PriorityQueue<>(new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
return o1.dist - o2.dist;
}
});
for(int i = 0; i < points.length; i++) {
pq.add(new Pair(points[i][0], points[i][1]));
}
int num = 0;
int[][] ret = new int[K][2];
while(num < K) {
Pair cur = pq.poll();
ret[num][0] = cur.x;
ret[num][1] = cur.y;
num++;
}
return ret;
}
}
class Pair {
int x;
int y;
int dist;
public Pair(int x, int y) {
this.x = x;
this.y = y;
this.dist = x*x + y*y;
}
}
代码 2 更好的解法, 参考 215 题求第k大数的解法。
class Solution {
private Random random = new Random();
public int[][] kClosest(int[][] points, int K) {
if(K == points.length)
return points;
int start = 0, end = points.length - 1;
int index = 0;
while (start <= end) {
index = partition(points, start, end);
if (index == K) {
break;
}
if (index > K) {
end = index - 1;
} else {
start = index + 1;
}
}
int[][] result = new int[index][2];
for (int i = 0; i < index; i++) {
result[i] = points[i];
}
return result;
}
private int partition(int[][] points, int start, int end) {
int rd = start + random.nextInt(end - start + 1);
int[] target = points[rd];
swap(points, rd, end);
int left = start, right = end - 1;
while (left <= right) {
while (left <= right && !isLarger(points[left], target)) left++;
while (left <= right && isLarger(points[right], target)) right--;
if (left <= right) {
swap(points, left, right);
left++;
right--;
}
}
swap(points, left, end);
return left;
}
private void swap(int[][] points, int i1, int i2) {
int[] temp = points[i1];
points[i1] = points[i2];
points[i2] = temp;
}
// return true if p1 dist is larger than p2
private boolean isLarger(int[] p1, int[] p2) {
return p1[0] * p1[0] + p1[1] * p1[1] > p2[0] * p2[0] + p2[1] * p2[1];
}
}