python優先隊列heapq

https://blog.csdn.net/weixin_39702559/article/details/110971925

#coding:gbk
import heapq
 
# 使用heapq實現優先隊列
#定義一個可比較對象
class CompareAble:
    def __init__(self,priority,jobname):
        self.priority = priority
        self.jobname = jobname
 
    def __lt__(self, other):
        if self.priority <= other.priority:
            return False
        else:
            return True
 
joblist = []
 
heapq.heappush(joblist,CompareAble(80,'eat'))
heapq.heappush(joblist,CompareAble(70,'a write plan2'))
heapq.heappush(joblist,CompareAble(70,'write plan'))
heapq.heappush(joblist,CompareAble(90,'sleep'))
heapq.heappush(joblist,CompareAble(100,'write code'))
 
while joblist:
    task = heapq.heappop(joblist)
    print(task.priority,task.jobname)
 
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Status:
    def __init__(self, val=0, ptr=None):
        self.val = val
        self.ptr = ptr
    
    def __lt__(self, other):
        if self.val > other.val:
            return False
        else:
            return True

class Solution:

    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        if lists == []:
            return None
        lists_len = len(lists)

        # 優先隊列
        import heapq
        que = []

        for li in lists:
            if li:
                heapq.heappush(que, Status(li.val, li))
            
        head = ListNode()
        tail = head
        while que:
            f = heapq.heappop(que)
            tail.next = f.ptr
            tail = tail.next
            if f.ptr.next:
                heapq.heappush(que, Status(f.ptr.next.val, f.ptr.next))
            
        return head.next

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章