合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力,两两合并,最后全合
# 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:
if len(lists)==0:
return None
if len(lists)==1:
return lists[0]
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
'''
两两合并
'''
#2
if not l1 or not l2:
return l1 if l1 else l2
if l1.val<=l2.val:
head=l1
l1=l1.next
else:
head=l2
l2=l2.next
l3=head
#print (head,l1)
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
#print(head)
if not l1:
l3.next=l2
elif not l2:
l3.next=l1
return head
res=lists[0]
for i in lists[1:]:
res=mergeTwoLists(i,res)
return res
分治+两两合并
主要在循环处加了inter作为合并之后的跳跃步数
# 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:
if len(lists)==0:
return None
if len(lists)==1:
return lists[0]
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
'''两两合并'''
#2
if not l1 or not l2:
return l1 if l1 else l2
if l1.val<=l2.val:
head=l1
l1=l1.next
else:
head=l2
l2=l2.next
l3=head
#print (head,l1)
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
#print(head)
if not l1:
l3.next=l2
elif not l2:
l3.next=l1
return head
#分治,主要看inter和n之间的配合
inter=1
n=len(lists)
while inter<n:
for i in range(0,n-inter,2*inter):
lists[i]=mergeTwoLists(lists[i],lists[i+inter])
inter*=2
return lists[0]
优先队列(极大二叉堆实现)