-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23.merge-k-sorted-lists.py
49 lines (41 loc) · 1.3 KB
/
23.merge-k-sorted-lists.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 230409
# 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):
compare = []
empty_count = 0
res_head, res_tail = None, None
for i in range(len(lists)):
compare.append(lists[i])
if lists[i] == None:
empty_count += 1
idx = -2
while empty_count < len(lists) and idx != -1:
idx = self.find_min_idx(compare)
if idx == -1:
continue
if res_head == None:
res_head = compare[idx]
res_tail = compare[idx]
else:
res_tail.next = compare[idx]
res_tail = res_tail.next
compare[idx] = compare[idx].next
if compare[idx] == None:
empty_count += 1
return res_head
# return index of smallest value within a comparison list
def find_min_idx(self, comparison_list):
min = None
res = -1
for i, node in enumerate(comparison_list):
if node == None:
continue
if min == None or node.val < min:
min = node.val
res = i
return res