1class Solution:
2 def mergeKLists(self, lists: List[ListNode]) -> ListNode:
3
4 setattr(ListNode, "__lt__", lambda self, other: self.val <= other.val)
5
6 pq = []
7 for l in lists:
8 if l:
9 heapq.heappush(pq, l)
10
11 out = ListNode(None)
12 head = out
13 while pq:
14 l = heapq.heappop(pq)
15 head.next = l
16 head = head.next
17 if l and l.next:
18 heapq.heappush( pq, l.next)
19
20 return out.next
21
1from queue import PriorityQueue
2
3class PqElement(object):
4 def __init__(self, value: int):
5 self.val = value
6
7 #Custom Compare Function (less than or equsal)
8 def __lt__(self, other):
9 """self < obj."""
10 return self.val > other.val #Compare Function For Max Heap - Max element on top
11
12 #Print each element function
13 def __repr__(self):
14 return f'PQE:{self.val}'
15
16#Usage-
17pq = PriorityQueue()
18pq.put(PqElement(v)) # Add Item - O(Log(n))
19topValue = pq.get() # Pop top item - O(1)
20topValue = pq.queue[0].val # Get top value - O(1)
21pqSize = pq.qsize() # Provide Queue Size - O(1)
22isEmpty = pq.empty() # Is PQ is empty
1from queue import PriorityQueue
2
3class PqElement(object):
4 def __init__(self, value: int):
5 self.val = value
6
7 #Custom Compare Function (less than or equsal)
8 def __lt__(self, other):
9 """self < obj."""
10 return self.val > other.val
11
12 #Print each element function
13 def __repr__(self):
14 return f'PQE:{self.val}'
15
16#Usage-
17pq = PriorityQueue()
18pq.put(PqElement(v)) #Add Item - O(Log(n))
19topValue = pq.get() #Pop top item - O(1)
20topValue = pq.queue[0].val #Get top value - O(1)