Leetcode 973. K Closest Points to Origin

2021-08-13 11:56:22 浏览数 (1)

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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/

0 人点赞