Merge k Sorted Lists
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists or len(lists) == 0 :
return None
while len(lists) > 1 :
ml = []
for i in range(0, len(lists), 2):
l1 = lists[i]
l2 = lists[i+1] if (i+1) <len(lists) else None
ml.append(self.mergeTwoLists(l1,l2))
lists = ml
return lists[0]
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
d = ListNode()
p = d
while l1 and l2 :
if l1.val < l2.val :
p.next = l1
l1 = l1.next
else :
p.next = l2
l2 = l2.next
p = p.next
if l1 :
p.next = l1
else :
p.next = l2
return d.next
Explaination :
Comments
Post a Comment