您的位置:首页 > 其它

find k closest point to origin point in 2d plane

2016-07-18 08:48 411 查看
public List<Point> findKClosest(Point[] p, int k) {
List<Point> res = new LinkedList<>();
PriorityQueue<Point> queue = new PriorityQueue<>(11, new Comparator<Point>(){
@Override
public int compare(Point a, Point b){
return b.x * b.x + b.y * b.y - a.x * a.x - a.y * a.y;
}
});
for (Point point: p) {
if (queue.size() < k) {
queue.offer(point);
} else {
Point a = queue.poll();
if (point.x * point.x + point.y * point.y - a.x * a.x - a.y * a.y < 0) {
queue.poll();
queue.offer(point);
}
}
}
while (!queue.isEmpty()) {
res.add(queue.poll());
}
return res;
}

class Point {
int x;
int y;
public Point (int x, int y) {
this.x = x;
this.y = y;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: