topk 问题的解决方法和分析

1.全排序方法

class Solution:
    def kClosest(self, points, K):
        points.sort(key= lambda x: x[0]**2 + x[1]**2)
        return points[:K]

2. 堆排序的方法

import heapq
class Solution:
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
return heapq.nsmallest(K, points, lambda p: p[0]**2 + p[1]**2)

猜你喜欢

转载自www.cnblogs.com/gylhaut/p/11986255.html