The K Closest Points to Origin problem involves finding the K
points closest to the origin (0, 0) from a given list of points in a 2D plane. The distance is calculated using the Euclidean distance formula.
This problem can be efficiently solved using a max-heap to track the farthest points among the closest K
points.
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a, b) -> Integer.compare(
b[0] * b[0] + b[1] * b[1],
a[0] * a[0] + a[1] * a[1]
)
);
// Step 1: Add points to the heap
for (int[] point : points) {
maxHeap.offer(point);
if (maxHeap.size() > k) {
maxHeap.poll(); // Remove the farthest point
}
}
// Step 2: Extract the K closest points
int[][] result = new int[k][2];
while (k > 0) {
result[--k] = maxHeap.poll();
}
return result;
}
}
O(N log K)
โ Adding and removing elements from the heap.O(N log K)
.Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
- The distance of (1, 3) from the origin is sqrt(10).
- The distance of (-2, 2) from the origin is sqrt(8).
- The closest point is (-2, 2).
K
points.K
greater than the number of points.K
for optimal performance.