K Closest Points to Origin
Advertisement
Problem
Return the k closest points to the origin. Distance = x² + y² (no need for square root).
Key insight: Max-heap of size k comparing squared distances. If new distance < heap max, replace.
Solutions
// C — sort by distance
// C++ — max-heap of size k
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
auto dist = [](vector<int>& p){ return p[0]*p[0] + p[1]*p[1]; };
priority_queue<pair<int,int>> maxH; // (dist, index)
for (int i = 0; i < (int)points.size(); i++) {
maxH.push({dist(points[i]), i});
if ((int)maxH.size() > k) maxH.pop();
}
vector<vector<int>> res;
while (!maxH.empty()) { res.push_back(points[maxH.top().second]); maxH.pop(); }
return res;
}
// Java
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> maxH = new PriorityQueue<>(
(a, b) -> (b[0]*b[0]+b[1]*b[1]) - (a[0]*a[0]+a[1]*a[1]));
for (int[] p : points) {
maxH.offer(p);
if (maxH.size() > k) maxH.poll();
}
return maxH.toArray(new int[k][]);
}
// JavaScript
function kClosest(points, k) {
const dist = p => p[0]*p[0] + p[1]*p[1];
points.sort((a, b) => dist(a) - dist(b));
return points.slice(0, k);
}
# Python
import heapq
def kClosest(points, k):
# Max-heap (negate distance)
heap = []
for x, y in points:
d = -(x*x + y*y)
heapq.heappush(heap, (d, x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]
Complexity
- Heap: O(n log k)
- Sort: O(n log n)
- Quickselect: O(n) average
Advertisement
← Previous
Task Scheduler