1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
public class {
public Point[] kClosest(Point[] points, Point origin, int k) { PriorityQueue<Point> pq = new PriorityQueue<Point>(k, new Comparator<Point>() { public int compare(Point a, Point b) { int diff = getDistance(b, origin) - getDistance(a, origin); if (diff == 0) { diff = b.x - a.x; } if (diff == 0) { diff = b.y - a.y; } return diff;
}
} ); Point[] result = new Point[k];
for (int i = 0; i < points.length; i++) { pq.offer(points[i]); if (pq.size() > k) { pq.poll(); } } while (!pq.isEmpty()) { result[--k] = pq.poll(); } return result;
} private int getDistance(Point a, Point b) { return (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y); } }
|
近期评论