- Top k Largest Numbers
Similar to K closest points, so no notes for this problem.
Given an integer array, find the top k largest numbers in it.
Example
Given [3,10,1000,-99,4,100] and k = 3.
Return [1000, 100, 10].
import heapq # cannot be placed in `class`
class Solution:
"""
@param nums: an integer array
@param k: An integer
@return: the top k largest numbers in array
"""
def topk(self, nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
result = heap.reverse()
return heap.reverse()
- Construct a comparator:
网友评论