标签:col wan answer 就是 -o 2-2 cep 实现 坐标
最接近原点的K个点。题意是给一些点的坐标(以二维数组表示)和一个数字K。求距离最靠近原点的前K个点。例子,
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.)
求前K个XX的问题,十有八九可以用heap/priority queue解决,这个题也不例外。我这里给出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 }
[LeetCode] 973. K Closest Points to Origin
标签:col wan answer 就是 -o 2-2 cep 实现 坐标
原文地址:https://www.cnblogs.com/aaronliu1991/p/12485469.html