[LeetCode] 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 个点。
给定一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点,并且是一个整数 k ,返回离原点 (0,0) 最近的 k 个点。
这里,平面上两点之间的距离是 欧几里德距离( √(x1 - x2)2 + (y1 - y2)2 )。
你可以按 任何顺序 返回答案。除了点坐标的顺序之外,答案 确保 是 唯一 的。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/k-closest-points-to-origin
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给一些点的坐标(以二维数组表示)和一个数字 K。求距离最靠近原点的前 K 个点。
求前 K 个XX的问题,十有八九可以用 heap/priority queue 解决,这个题也不例外。我这里给出 pq 的解法,用 pq 创建一个最小堆,将每个坐标与原点的距离加入 pq。求距离就是初中数学的勾股定理。
时间O(nlogk)
空间O(n)
Java实现
1 class Solution { 2 public int[][] kClosest(int[][] points, int K) { 3 PriorityQueue<int[]> pq = new PriorityQueue<>(K, 4 (o1, o2) -> o1[0] * o1[0] + o1[1] * o1[1] - o2[0] * o2[0] - o2[1] * o2[1]); 5 for (int[] point : points) { 6 pq.add(point); 7 } 8 int[][] res = new int[K][2]; 9 for (int i = 0; i < K; i++) { 10 res[i] = pq.poll(); 11 } 12 return res; 13 } 14 }
这道题还有一个类似快速排序的做法,也值得掌握。
时间O(n), worst case, O(n^2)
空间O(1)
Java实现
1 class Solution { 2 public int[][] kClosest(int[][] points, int K) { 3 int len = points.length; 4 int l = 0; 5 int r = len - 1; 6 while (l <= r) { 7 int mid = helper(points, l, r); 8 if (mid == K) { 9 break; 10 } 11 if (mid < K) { 12 l = mid + 1; 13 } else { 14 r = mid - 1; 15 } 16 } 17 return Arrays.copyOfRange(points, 0, K); 18 } 19 20 private int helper(int[][] points, int left, int right) { 21 int[] pivot = points[left]; 22 while (left < right) { 23 while (left < right && compare(points[right], pivot) >= 0) { 24 right--; 25 } 26 points[left] = points[right]; 27 while (left < right && compare(points[left], pivot) <= 0) { 28 left++; 29 } 30 points[right] = points[left]; 31 } 32 points[left] = pivot; 33 return left; 34 } 35 36 private int compare(int[] p1, int[] p2) { 37 return p1[0] * p1[0] + p1[1] * p1[1] - p2[0] * p2[0] - p2[1] * p2[1]; 38 } 39 }
相关题目
215. Kth Largest Element in an Array