21. 合并两个有序链表
此题同剑指offer16题。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res = head = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
head.next = l1 or l2
return res.next
23. 合并K个排序链表
方法1:利用堆将所有链表都放在堆中,每次取出堆顶元素
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i] :
heapq.heappush(head, (lists[i].val, i))
lists[i] = lists[i].next
while head:
val, idx = heapq.heappop(head)
p.next = ListNode(val)
p = p.next
if lists[idx]:
heapq.heappush(head, (lists[idx].val, idx))
lists[idx] = lists[idx].next
return dummy.next
方法2:分治
class Solution(object):
def mergeKLists(self, lists):
if not lists:
return None
# 通过mid将数组一分为二,并不断缩小规模,当规模为1时返回并开始合并
# 通过合并两个链表,不断增大其规模,整体看就是不断缩小-最后不断扩大的过程
def helper(begin,end):
if begin==end:
return lists[begin]
mid = begin+(end-begin)/2
left = helper(begin,mid)
right = helper(mid+1,end)
return merge(left,right)
# 合并两个有序链表
def merge(a,b):
if not (a and b):
return a if a else b
if a.val<=b.val:
a.next = merge(a.next,b)
return a
else:
b.next = merge(a,b.next)
return b
return helper(0,len(lists)-1)