美文网首页
2018-10-21 Top k Largest Numbers

2018-10-21 Top k Largest Numbers

作者: WenshengL | 来源:发表于2018-10-22 08:43 被阅读0次
  1. 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:

相关文章

网友评论

      本文标题:2018-10-21 Top k Largest Numbers

      本文链接:https://www.haomeiwen.com/subject/nljwzftx.html