题解
思路
代码
- 归并排序 python3版本
# 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: List[ListNode]) -> ListNode:
def merge(lists, l, r):
if l == r: return lists[l]
mid = (l+r) // 2
l1 = merge(lists, l, mid)
l2 = merge(lists, mid+1, r)
return mergeTwoLists(l1, l2)
def mergeTwoLists(l1, l2):
dum = cur = ListNode(None)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dum.next
if not lists: return
return merge(lists, 0, len(lists)-1)
- 优先堆排序(Python2!)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
### 0104 优先堆排序(88 ms,18.9 MB)
def mergeKLists(self, lists):
if not lists: return
dummy = cur = ListNode(None)
# 引入堆
import heapq
heap = []
# 第一次将所有链表的第一个元素入堆,并排序
for head in lists:
# (head.val, head)将会根据第一个元素head.val排序
# 而head是与head.val绑定,以找到正确的顺序位置
if head: heapq.heappush(heap, (head.val, head))
# 当堆非空时,
while heap:
# 最小元素出堆:第一个值val不需要,仅需要它所在的链表(头节点)head
_, head = heapq.heappop(heap)
# 辅助节点指向当前最小的链表,并后移
cur.next = head
cur = cur.next
# 若当前链表还有后续节点,则需要将后续的一个节点入堆,并进行排序(同上)
if head.next: heapq.heappush(heap, (head.next.val, head.next))
cur.next = None # 可选:将最后一个节点指向空
return dummy.next # 返回伪头节点
- 归并链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
### 0104 归并链表(120 ms,18.3 MB)
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists: return
return self.merge(lists, 0, len(lists) - 1)
# 递归合并链表集合
def merge(self, lists, l, r):
# 递归终止条件
if l == r: return lists[l]
# 二分法
mid = (l + r) // 2
l1 = self.merge(lists, l, mid)
l2 = self.merge(lists, mid + 1, r)
return self.mergeTwoLists(l1, l2)
# 合并2个链表(前面保证了两个链表不会为空)
def mergeTwoLists(self, l1, l2):
dummy = cur = ListNode(None)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dummy.next