To efficiently find the K closest points to the origin, we need a strategy that maintains
optimal candidates.
We use a
max heap
to
maintain the K smallest distances.
For each point, we
calculate its squared distance
(avoiding square root for efficiency) and
push it into the heap
.
When the heap size exceeds K, we
remove the top element of the heap
.
This ensures we always keep the K closest points in the heap.
class Solution { public int[][] kClosest(int[][] points, int k) { PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->Integer.compare(b[0],a[0])); for(int idx=0;idx<points.length;idx++){ int distance = points[idx][0]*points[idx][0] + points[idx][1]*points[idx][1]; pq.offer(new int[]{distance,idx}); if(pq.size()>k) pq.poll(); } List<int[]> ans = new ArrayList<>(); while(!pq.isEmpty()){ int idx = pq.poll()[1]; ans.add(points[idx]); } return ans.toArray(new int[ans.size()][2]); } }
We process n points, with each heap operation taking O(log k) time since we maintain at most k elements.
The heap stores at most k elements, and the output requires O(k) space.