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.