Find the K closest points to a target point in a 2D plane.
class Point {
public int x;
public int y; public Point(int x, int y) {
this.x = x;
this.y = y;
}
} class Solution { public List<Point> findKClosest(Point[] points, int k, Point p) { // max heap
PriorityQueue<Point> pq = new PriorityQueue<>(, new Comparator<Point>() {
@Override
public int compare(Point a, Point b) {
double d1 = distance(a, p);
double d2 = distance(b, p);
if (d1 == d2)
return ;
if (d1 < d2)
return ;
return -;
}
}); for (int i = ; i < points.length; i++) {
pq.offer(points[i]); if (pq.size() > k) {
pq.poll();
}
} List<Point> x = new ArrayList<>();
while (!pq.isEmpty())
x.add(pq.poll()); return x;
} private double distance(Point p1, Point p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
}