2018-10-21 Top k Largest Numbers

2018-10-22  本文已影响0人  WenshengL
  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()
上一篇下一篇

猜你喜欢

热点阅读