【LeetCode】 973. K Closest Points to Origin 最接近原点的 K 个点(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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
题目大意
我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。
(这里,平面上两点之间的距离是欧几里德距离。)
你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
解题方法
一般计算 K 个最值问题都用堆排序,下面用两种排序算法说明下为什么堆排序更快
插入排序
- 采用插入排序的方法
- 时间复杂度 O(nlogK)
class Solution {
public int[][] kClosest(int[][] points, int K) {
List<int[]> list = new ArrayList<>();
for (int i = 0; i < points.length; i++) {
insert(list, points, i, K);
}
int[][] res = new int[K][2];
for (int i = 0; i < list.size(); i++) {
res[i] = points[list.get(i)[0]];
}
return res;
}
// list[0]: index, list[1]: distance
public void insert(List<int[]> list, int[][] points, int index, int K) {
int sum = points[index][0] * points[index][0] + points[index][1] * points[index][1];
if (list.size() >= K && sum > list.get(list.size() - 1)[1]) return;
if (list.size() >= K) list.remove(list.size() - 1);
int start = 0;
int end = list.size() - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (list.get(mid)[1] == sum) {
start = mid;
break;
} else if (list.get(mid)[1] > sum) {
end = mid - 1;
} else {
start = mid + 1;
}
}
list.add(start, new int[]{index, sum});
}
}
执行耗时:52 ms,击败了14.21% 的Java用户
内存消耗:47.3 MB,击败了40.28% 的Java用户
堆排序
- 采用堆排序的方法
- 时间复杂度 O(Klogn):因为 K < n,所以 Klogn < nlogK,堆排序更快
class Solution {
public int[][] kClosest(int[][] points, int K) {
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> (b[1] - a[1]));
for (int i = 0; i < K; i++) {
queue.offer(new int[]{i, points[i][0] * points[i][0] + points[i][1] * points[i][1]});
}
for (int i = K; i < points.length; i++) {
int dis = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (dis < queue.peek()[1]) {
queue.poll();
queue.offer(new int[]{i, dis});
}
}
int[][] res = new int[K][2];
for (int i = 0; i < K; i++) {
res[i] = points[queue.poll()[0]];
}
return res;
}
}
执行耗时:31 ms,击败了56.28% 的Java用户
内存消耗:47.6 MB,击败了21.72% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)