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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。