LintCode 544 [Top k Largest Numbers]

原题

在一个数组中找到前K大的数

样例
给出 [3,10,1000,-99,4,100], k = 3.
返回 [1000, 100, 10]

解题思路

  • 方法一:快速排序,然后取出前k大的数。时间复杂度O(n*logn + k)

  • 方法二:维护一个大小为k的最大堆/最小堆,代码如下。时间复杂度为O(n * logk)

  • 关于Heap

  • 在python中有两个接口:heapqQueue.PriorityQueue。其中PriorityQueue module is using the heapq module which is slower because it adds locks, encapsulation, and a nice object oriented API.

  • heapq的使用:

    • heapq.heappush: Push the value item onto the heap, maintaining the heap invariant.
    • heapq.heappop: Pop and return the smallest item from the heap, maintaining the heap invariant.
    • heapq.heapify: Transform list x into a heap, in-place, in linear time.
  • Queue.PriorityQueue的使用 (myqueue = Queue.PriorityQueue)

    • myqueue.put()
    • myqueue.get()
    • myqueue.qsize()
    • myqueue.empty()

完整代码

import Queue

class Solution:
    '''
    @param {int[]} nums an integer array
    @param {int} k an integer
    @return {int[]} the top k largest numbers in array
    '''
    def topk(self, nums, k):
        # Write your code here
        res = []
        if not nums or k == 0:
            return res
            
        MaxHeap = Queue.PriorityQueue()
        for num in nums:
            MaxHeap.put(-num)
        
        for i in range(k):
            res.append(-MaxHeap.get())
        
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • ――送给那些来过的人,多谢 “你见过荞麦花吗?” “唉?荞麦花,见过。” “那我敢肯定你的没我的好看!”我的...
    嘘星期五阅读 500评论 0 0
  • 刚开始,我以为只要真诚地对别人好,别人也会对我好,有些人是的,对他好,能记住,有些人啊,呵呵。 我想说得对值得对他...
    晟妹你好阅读 130评论 0 0
  • 我愿意与一座山为敌,只因母亲压在它的身下。 驻足 娘,我来了!带着劈开华山一条路的开天神斧。 来之前,我问过爹,我...
    钟大晓阅读 459评论 0 0
  • 一、GIT发展史 同生活中的许多伟大事件一样,Git 诞生于一个极富纷争大举创新的年代。Linux 内核开源项目有...
    小程故事多阅读 983评论 0 29