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;
}
}
find k closest point to origin point in 2d plane
最新推荐文章于 2023-08-30 16:17:39 发布