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)

 

posted @ 2019-12-04 22:35  流星小子  阅读(285)  评论(0编辑  收藏  举报