Leetcode 每日一题
题目链接: 973. 最接近原点的 K 个点
难度: 困难
解题思路: 自定义一个距离比较函数,距离小的在前。对列表进行排序,取前K个。
题解:
import functools as ft
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
# 距离计算
def cal_dist(point):
return point[0]*point[0] + point[1]*point[1]
# 比较函数
def dist_cmp(a, b):
if cal_dist(a) > cal_dist(b):
return 1
else:
return -1
points.sort(key = ft.cmp_to_key(dist_cmp))
# print(points)
return points[0:K]