-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeKSortedLists.py
33 lines (31 loc) · 974 Bytes
/
MergeKSortedLists.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
# https://www.interviewbit.com/problems/merge-k-sorted-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
head = None
cur = None
while True:
minElem = float("inf")
minIndex = -1
for i in range(len(A)):
if not A[i]:
continue
if A[i].val < minElem:
minIndex = i
minElem = A[i].val
if minIndex == -1:
return head
else:
if not cur:
cur = A[minIndex]
head = cur
else:
cur.next = A[minIndex]
cur = cur.next
A[minIndex] = A[minIndex].next