2018-10-21 Top k Largest Numbers[M]

  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:
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,725评论 0 10
  • 可能我的爱太过于卑微,我没有勇气说出口。 因为你是优秀的,我和你直接太多的距离。 只能藏在心里无处诉说...
    晨曦微微阅读 261评论 0 0
  • dream 要是从感觉上来讲,昨晚上,是我与位神最近的一次…….吧? 暑假朋友间的走动让我俩频繁鬼混,尽管我在想,...
    ANOTHERFLY阅读 1,303评论 0 0
  • 假如回到大一,你最想做什么? 奇怪为什么我脑子里蹦出来的第一个想法居然是谈恋爱**,一大概是因为我最近看《微微一笑...
    布家米阅读 556评论 0 4
  • 婆媳关系总是存在那么一丝微妙,有的婆婆尽管很好,但是和儿媳妇还是合不来;有的儿媳妇很优秀,可是怎么也不能让婆婆满意...
    良知爸爸阅读 603评论 0 0

友情链接更多精彩内容