學習筆記 | 前 K 個高頻元素、優先隊列、最小堆

在這裏插入圖片描述
在這裏插入圖片描述

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        def shift(i,k):
            #維護最小堆
            while True:
                t= 2*i+1
                
                if t >= k :
                    return
                if t+1 < k and hashlist[t][1] > hashlist[t+1][1]:
                    t=t+1
                
                if hashlist[t][1] < hashlist[i][1]:
                    hashlist[t],hashlist[i] = hashlist[i],hashlist[t]                   
                    i=t
                else:
                    return


        #建立哈希表
        hashmap={}
        for i in nums:
            hashmap[i]=hashmap.get(i,0)+1
        
        #將哈希錶轉爲二維列表
        hashlist=[ [key,v] for key, v in hashmap.items() ]

        #建立K個元素的最小堆
        for i in range(k/2,-1,-1):
            shift(i,k)
            
        #剩餘依次和堆頂比較
        for i in range(k,len(hashlist)):
            if hashlist[i][1] >= hashlist[0][1]:
                hashlist[0] = hashlist[i]
                shift(0,k)
                
        return [hashlist[i][0] for i in range(k-1,-1,-1)]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章