题目描述:
我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。(这里,平面上两点之间的距离是欧几里德距离。)你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
示例:
输入:points = [[1,3],[-2,2]], K = 1
输出:[[-2,2]]
解释:
(1, 3) 和原点之间的距离为 sqrt(10),
(-2, 2) 和原点之间的距离为 sqrt(8),
由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。
我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。
本人答案:
思路:利用冒泡排序在每轮排序完成时找到距离原点最近的一个点(其他能类似算法也可以)
class Solution {
public int[][] kClosest(int[][] points, int K) {
if(K>points.length) return points;
int i=0, j=0;
int[] temp = new int[2];
int[][] result = new int[K][];
for(i=0; i<K; ++i){
for(j=0; j<points.length-i-1; ++j){
if(Oc_distance(points[j])<Oc_distance(points[j+1])){
temp = points[j];
points[j] = points[j+1];
points[j+1] = temp;
}
}
result[i] = points[j];
}
return result;
}
public static int Oc_distance(int[] point){
return (int) point[0]*point[0] + point[1]*point[1];
}
}
大神答案1:
class Solution:
def kClosest(self, points, K) :
a = lambda x :x[0]**2 + x[1]**2
points.sort(key = a)
return points[:K]
注:本答案来自LeeCode ID为“msoak”的用户
大神答案2:
java中的PriorityQueue默认是小根堆,想要使用大根堆重写一下比较器即可
class Solution {
public int[][] kClosest(int[][] points, int K) {
PriorityQueue<Node> pq = new PriorityQueue<>((a,b)->{return b.val-a.val;});
for(int i = 0;i < points.length;i++){
Node n = new Node(points[i]);
if(pq.size() < K){
//直接放入
pq.offer(n);
}else{
Node n1 = pq.peek();
//大于 最小距离
if(n1.val > n.val){
//弹出 放入
pq.poll();
pq.offer(n);
}
}
}
int [][] res = new int[pq.size()][2];
int i = 0;
for(Node node : pq){
res[i++] = node.arr;
}
return res;
}
class Node {
int val;
int[] arr;
public Node(int[] arr){
this.arr = arr;
val = arr[0]*arr[0] + arr[1]*arr[1];
}
}
}
注:本答案来自LeeCode ID为“chuangkel"的用户
更多可参考:讨论