K Closest Points to Origin
LeetCode 973 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Max-heap of size k on squared distance.
నేను K Closest Points to Origin (LeetCode 973) ను ఇలా పరిష్కరించాను — Top K ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
Approach
- 1
Squared distance x² + y² (no square root needed).
- 2
Heap smaller than k → push.
- 3
Closer than the heap's farthest → pop it and push the new point.
- 4
The heap holds the answer.
నేను ఎలా పరిష్కరించాను
Max-heap of size kPythonO(n log k) time · O(k) space
import heapq
class Solution:
def kClosest(self, points, k):
pq = [] # max-heap via negative distance
for point in points:
x, y = point
distance = x ** 2 + y ** 2
if len(pq) < k:
heapq.heappush(pq, (-distance, point))
elif distance < -pq[0][0]:
heapq.heappop(pq)
heapq.heappush(pq, (-distance, point))
return [item[1] for item in pq]K Closest Points to Origin — తరచూ అడిగే ప్రశ్నలు
K Closest Points to Origin వెనుక ఉన్న intuition ఏమిటి?
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
K Closest Points to Origin (LeetCode 973) ను ఎలా పరిష్కరించాలి?
1. Squared distance x² + y² (no square root needed). 2. Heap smaller than k → push. 3. Closer than the heap's farthest → pop it and push the new point. 4. The heap holds the answer.
K Closest Points to Origin యొక్క time, space complexity ఎంత?
Time: O(n log k). Space: O(k). (Accepted approach: Max-heap of size k.)
K Closest Points to Origin లో సాధారణ పొరపాట్లు ఏమిటి?
Comparing squared distances avoids floating-point roots.