描述
給定一些 points 和一個 origin,從 points 中找到 k 個離 origin 最近的點爪幻。按照距離由小到大返回塑顺。如果兩個點有相同距離,則按照x值來排序畅哑;若x值也相同鳍徽,就再按照y值排序。
心得
復(fù)習(xí)了comparator的重寫敢课,與Arrays.sort()差不多阶祭,重寫comparator的compare函數(shù),可以實現(xiàn)自定義排序直秆。升序前減后濒募,降序后減前。
代碼
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
class Pair {
int x,y,d;
Pair(int x, int y, int d) {
this.x = x;
this.y = y;
this.d = d;
}
}
public class Solution {
/**
* @param points: a list of points
* @param origin: a point
* @param k: An integer
* @return: the k closest points
*/
public int distance(Point point, Point origin) {
int x = point.x - origin.x;
int y = point.y - origin.y;
int result = x*x+y*y;
return result;
}
public Point[] kClosest(Point[] points, Point origin, int k) {
// write your code here
Pair[] p = new Pair[points.length];
Point[] result5 = new Point[k];
for(int i = 0; i < points.length;i++) {
Pair tmp9 = new Pair(points[i].x,points[i].y,distance(points[i], origin));
p[i] = tmp9;
}
PriorityQueue<Pair> queue = new PriorityQueue(k,new Comparator<Pair>(){
@Override //重寫compare函數(shù)
public int compare(Pair a, Pair b) {
if(a.d == b.d) {
if(a.x == b.x) {
return a.y - b.y;
}
else {
return a.x - b.x;
}
}
else {
return a.d - b.d;
}
}
});
for(int i =0; i < p.length; i++) {
queue.offer(p[i]);
}
for(int i = 0; i < k;i++) {
Pair tmp = queue.poll();
Point tmp2 = new Point(tmp.x,tmp.y);
result5[i] = tmp2;
}
return result5;
}
}