K Closest Points
Question (LI.612)
Example
I: [(4,6), (4,7), (4,4), (2,5), (1,1)], (0,0), 3
O: [(1,1), (2,5), (4,4)]Approach
Code
// compute the Euclidean distance
private double eucDist (Point origin, Point pt) {
return Math.pow((origin.x - pt.x), 2) + Math.pow((origin.y - pt.y), 2);
}
public Point[] kClosest(Point[] points, Point origin, int k) {
Point[] result = new Point[k];
// create a comparator with distance function
Comparator<Point> PtComp = (Point pt1, Point pt2) -> {
int closeness = (int) (eucDist(origin, pt1) - eucDist(origin, pt2));
if (closeness != 0) return closeness;
else if (pt1.x != pt2.x) return pt1.x - pt2.x;
else return pt1.y - pt2.y;
};
// create a max heap of size k
// either reverseOrder() or flip pt1 and pt2 would work
Queue<Point> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder(PtComp));
// add points to the max heap if bigger then kick off the max
for (Point pt : points) {
if (maxHeap.size() == k) {
if (eucDist(origin, pt) < eucDist(origin, maxHeap.peek())) {
maxHeap.poll();
maxHeap.offer(pt);
}
} else {
maxHeap.offer(pt);
}
}
// max heap to result array (ascending)
int index = k - 1;
while (!maxHeap.isEmpty()) {
result[index--] = maxHeap.poll();
}
return result;
}Time & Space Complexity
Memoization
Last updated