# 合并k个已排序的链表

class ListNode:# Definition for singly-linked list.
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode[]} lists
# @return {ListNode}
def mergeKLists_0(self, lists): #方法1
lists = [list for list in lists if list is not None]
if len(lists)<=0:
return lists
l=lists[0]
for i in range(1,len(lists)):
l=self.merge2lists(l,lists[i])
return l

def merge2lists(self,list_1,list_2):
if list_1 is None:
return list_2
if list_2 is None:
return list_1
if list_1.val>=list_2.val:
else:
return head

    def mergeKLists(self, lists):
lists = [list for list in lists if list is not None]
if len(lists)<=0:
return lists
if len(lists)==1:
return lists[0]
d=[]
for i in range(0,len(lists)-1,2):
l=self.merge2lists(lists[i],lists[i+1])
d.append(l)
if len(lists)%2==1:
d.append(lists[len(lists)-1])
return self.mergeKLists(d)

merge2lists(n,m)平均需要比较(m+n)/2$(m+n)/2$O(n+m)$O(n+m)$

“方法1”，完成所有的合并的时间复杂度为O(nk2)=O((n+n)+(2n+n)+...+((k1)n+n))=O((k1)kn/2+(k1)n)$O(nk^2)=O((n+n)+(2n+n)+...+((k-1)n+n))=O((k-1)*kn/2+(k-1)n)$
“方法2”，每次递归的时候总共需要比较O(nk)$O(nk)$次，一共log(k)$log(k)$次递归，所以算法复杂度为O(nklog(k))$O(nklog(k))$

• 本文已收录于以下专栏：

## leetCode 23. Merge k Sorted Lists (合并k个排序链表) 解题思路和方法

Merge k Sorted Lists  Merge k sorted linked lists and return it as one sorted list. Analyze and des...

## LeetCode 23 Merge k Sorted Lists（合并K个已排序链表）

• NoMasp
• 2015-11-12 17:30
• 2888