leetcode 21. 合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
l_new = ListNode(None)
if l1.val < l2.val:
l_new.val = l1.val
l_new.next = self.mergeTwoLists(l1.next, l2)
else:
l_new.val = l2.val
l_new.next = self.mergeTwoLists(l1, l2.next)
return l_new
leetcode 23. 合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
length = len(lists)
if length == 0:
return None
if length == 1:
return lists[0]
if length == 2:
return self.merge2Lists(lists[0], lists[1])
mid = length // 2
left = self.mergeKLists(lists[:mid])
right = self.mergeKLists(lists[mid:])
return self.merge2Lists(left, right)
# 先合并两个排序链表, 再用分治法进行全部合并
def merge2Lists(self, list_1, list_2):
if not list_1:
return list_2
if not list_2:
return list_1
list_new = ListNode(None)
if list_1.val < list_2.val:
list_new.val = list_1.val
list_new.next = self.merge2Lists(list_1.next, list_2)
else:
list_new.val = list_2.val
list_new.next = self.merge2Lists(list_1, list_2.next)
return list_new