K Closest Points to Origin
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the X-Y plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the X-Y plane is the Euclidean distance `(i.e., sqrt((x1 - x2)^2 + (y1 - y2)^2))`. You may return the answer in any order.
Examples
Constraints
1 <= k <= points.length <= 10^4-10^4 <= xi, yi <= 10^4
Approach
To find the `k` smallest distances, we can maintain a Max Heap of size `k`. Iterate through the points, calculate their squared distance from the origin (no need to compute the square root). Push the `[distance, x, y]` into the Max Heap. If the heap size exceeds `k`, pop the largest element (which is at the root). This ensures the heap only contains the `k` closest points. Finally, extract the points from the heap.
Complexity Analysis
This is O(K) space because we only keep K elements in the heap.
class Solution { public int[][] kClosest(int[][] points, int k) { // Max Heap: sort by distance descending 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]) ) ); for (int[] point : points) { maxHeap.offer(point); if (maxHeap.size() > k) { maxHeap.poll(); } } int[][] result = new int[k][2]; int i = 0; while (!maxHeap.isEmpty()) { result[i++] = maxHeap.poll(); } return result; }}