Leetcode 973. K Closest Points to Origin
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 973. K Closest Points to Origin相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,依次计算与原点的距离,然后排序取前k
个即可。
- Version 1
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
n = len(points)
distances = [0] * n
for index, (x, y) in enumerate(points):
distances[index] = x * x + y * y
indexes = sorted(list(range(n)), key=lambda i: distances[i])
return [points[i] for i in indexes[:k]]
# return sorted(points, key=lambda x: x[0] * x[0] + x[1] * x[1])[:k]
Reference
以上是关于Leetcode 973. K Closest Points to Origin的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 973. K Closest Points to Origin
Leetcode 973. K Closest Points to Origin
[Solution] 973. K Closest Points to Origin