-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23.py
33 lines (26 loc) · 847 Bytes
/
23.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import re
import collections
import itertools
import heapq
import bisect
import sys
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
heap = []
root = result = ListNode(None)
for i, list in enumerate(lists):
if list:
heapq.heappush(heap, (list.val, i, list))
while heap:
node = heapq.heappop(heap)
idx = node[1]
result.next = node[2]
result = result.next
if result.next:
heapq.heappush(heap, (result.next.val, idx, result.next))
return root.next