-
Notifications
You must be signed in to change notification settings - Fork 1
/
Leetcode - 23 # Merge k Sorted Lists.py
59 lines (40 loc) · 1.27 KB
/
Leetcode - 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
50
51
52
53
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Naive Approach - Not very Optimal
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l3 = ListNode()
answer = l3
while l1 and l2:
if l1.val <= l2.val:
l3.next = l1
l1 = l1.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
if l1:
l3.next = l1
if l2:
l3.next = l2
return answer.next
# we will merge 2 lists
# And store the output in list1 (0th position)
# And then we will merge list1 with third1
# And then we will merge list1 with fourth
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if len(lists) == 0:
return None
if len(lists) == 1:
return lists[0]
j = 1
n = len(lists)
while j < n:
# Storing the output at 0th Index
lists[0] = self.mergeTwoLists(lists[0], lists[j])
j = j + 1
# returning the 0th Index
return lists[0]