Leetcode 973. K Closest Points to Origin

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

K Closest Points to Origin

2. Solution

解析:Version 1,依次计算与原点的距离,然后排序取前k个即可。

  • Version 1
1
2
3
4
5
6
7
8
9
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

  1. https://leetcode.com/problems/k-closest-points-to-origin/
如果有收获,可以请我喝杯咖啡!