링크
k 개의 정렬된 연결리스트를 하나로 정렬하기
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
k = len(lists)
res = head = None
while any([h != None for h in lists]):
minIdx = 0
minVal = float('inf')
for idx in range(k):
if lists[idx] and lists[idx].val < minVal:
minIdx = idx
minVal = lists[idx].val
if not res:
res = head = lists[minIdx]
else:
head.next = lists[minIdx]
head = head.next
lists[minIdx] = lists[minIdx].next
return res
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
k = len(lists)
if k > 1:
list1 = self.mergeKLists(lists[:k//2])
list2 = self.mergeKLists(lists[k//2:])
return self.merge(list1, list2)
if k == 1:
return lists[0]
if k == 0:
return None
def merge(self, list1, list2) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
head = ptr = None
if list1.val <= list2.val:
head = ptr = list1
list1 = list1.next
else:
head = ptr = list2
list2 = list2.next
while list1 and list2:
if list1.val < list2.val:
ptr.next = list1
list1 = list1.next
else:
ptr.next = list2
list2 = list2.next
ptr = ptr.next
if list1:
ptr.next = list1
if list2:
ptr.next = list2
return head
I found that solution very popular and helpful:
https://www.youtube.com/watch?v=L-8LVBPmIpc&ab_channel=EricProgramming