Python heapq 構造大頂堆


參考:https://blog.csdn.net/baidu_27643275/article/details/88878612

heapq模塊可以接受元組對象,默認元組的第一個元素作為priority,即按照元組的第一個元素構成 小根堆,若第一個元素是原先的負數,則可以利用元組構造大頂堆,符合一般的升序需求

heappush( Q , tuple )

利用元組構建 大頂堆

from heapq import *

def FindMaxProfit(profits, key=lambda x: -x):
    maxHeap1 = []
    for i in range(len(profits)):
        heappush(maxHeap1, (-profits[i], profits[i])) # 大頂堆
        # heappush(maxHeap1, profits[i])  # 默認小頂堆
    return heappop(maxHeap1)

# for test
profits = [3, 2, 4, 9]
print(FindMaxProfit(profits))  # (-9, 9) 最大值是元組的第二個元素 9


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM