最接近原點的 K 個點
「K 最近點到原點」問題的詳細指南和 Python 實作。
1. 學習
「距離原點最近的 K 個點」問題是堆疊/優先權佇列部分的一個關鍵挑戰。
此實作著重於 Python 中的簡單層級邏輯。
在我們提供的解決方案中,我們優先考慮技術準確性和程式碼可讀性。
2. Real-World Applications
3. Visual Intuition
可視化最接近原點的 K 個點的邏輯流程。
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
仔細閱讀 K 最近點到原點的問題陳述。
2. Formulate brute force
起草一個簡單的迭代解決方案。
3. Identify inefficiency
尋找冗餘計算。
4. Optimize search path
使用散列或排序來加速該過程。
5. Final Implementation
清理生產標準代碼。
問題陳述
給定一個點數組,其中點[i] = [xi, yi] 表示 X-Y 平面上的點和整數 k,返回距離原點 (0, 0) 最近的 k 個點。
X-Y 平面上兩點之間的距離是歐幾里德距離(即 sqrt((x1 - x2)^2 + (y1 - y2)^2))。
您可以按任何順序返回答案。答案保證是唯一的(除了它的順序)。
寫一個函數 kClosest(points: List[List[int]], k: int) -> List[List[int]]。
- •1 <= k <= len(points) <= 10^4
- •-10^4 <= xi, yi <= 10^4
範例
points = [[1,3],[-2,2]], k = 1
[[-2,2]]
The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) to the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
points = [[3,3],[5,-1],[-2,4]], k = 2
[[3,3],[-2,4]]
The closest two points are (3, 3) and (-2, 4). (Order of elements in the output does not matter).
Need a Hint?
Edge Cases to Watch
- 空輸入結構
- 單元素輸入
- 大數值範圍
準備好解決了嗎?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
面試見解和變化
複雜度分析分解
為什麼時間: Directly evaluates all possibilities.
為什麼選擇太空: Uses standard local memory.
為什麼時間: Optimized paths reduce total operations.
為什麼選擇太空: May trade memory for speed.
最佳化解決方案Python程式碼
最佳化解決方案Python程式碼
import heapq
def k_closest_opt(points, k):
minHeap = []
for x, y in points:
dist = (x**2) + (y**2)
minHeap.append([dist, x, y])
heapq.heapify(minHeap)
res = []
while k > 0:
dist, x, y = heapq.heappop(minHeap)
res.append([x, y])
k -= 1
return res暴力破解代碼(劇透保護)
暴力破解代碼(劇透保護)
def k_closest_brute(points, k):
points.sort(key=lambda p: p[0]**2 + p[1]**2)
return points[:k]Algorithm Pattern Checklist
When dealing with Heap / Priority Queue data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。
Python 生成器:記憶體高效的迭代器
了解如何使用Python生成器和yield语句以最小的内存占用处理巨大的数据集。掌握生成器表達式。
如何在 Python 中將字串轉換為 Int(安全轉換和基數)
了解如何在 Python 中使用 int() 函數將字串轉換為整數。安全地處理錯誤並將數字從二進位、八進位或十六進位轉換。
Python 運算子備忘單
掌握 Python 中的算術、比較、邏輯、位元、賦值和恆等運算子。
Python 裝飾器與裝飾器設計模式:主要區別
比較 Python 裝飾器和經典的裝飾器設計模式。了解定義時函數包裝和使用可運行程式碼的執行時間動態物件組合之間的差異。