150強訪談簡單

最接近原點的 K 個點

「K 最近點到原點」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個點數組,其中點[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

範例

Example 1
Input
points = [[1,3],[-2,2]], k = 1
Output
[[-2,2]]
Explanation

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.

Example 2
Input
points = [[3,3],[5,-1],[-2,4]], k = 2
Output
[[3,3],[-2,4]]
Explanation

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.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。