给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
方案一:
原理:将多链合并为列,利用单链递增原理倒序插入表序合成一个list。遍历list(此时无需排序),生成单链。
缺陷:执行用时: 2080 ms 内存消耗: 18.2 MB
class Solution(object):
def mergeKLists(self, lists):
data = []
go = True
while go:
go = False
for i in range(len(lists)):
if(lists[i] != None):
if(data == [] or data[-1]<=lists[i].val):
data.append(lists[i].val)
else:
for _ in range(len(data)):
if(lists[i].val>data[-_-1]):
data.insert(-_,lists[i].val)
break
else:
data.insert(0,lists[i].val)
lists[i] = lists[i].next
if(lists[i] != None):
go = True
reList = ListNode()
p = reList
for _ in data:
reList.next = ListNode()
reList = reList.next
reList.val = _
return p.next
方案二:
原理:利用双链成单链特性,分而治之
结果:执行用时: 60 ms 内存消耗: 17.7 MB
class Solution:
def mergeTwoLists(self,A,B):
if(not A or not B):
return A if(A) else B
temp = ListNode()
p = temp
while A and B:
if(A.val < B.val):
temp.next = A
A = A.next
else:
temp.next =B
B= B.next
temp = temp.next
temp.next = A if(A) else B
return p.next
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if(len(lists) == 0):return None
temp = lists
while len(temp) != 1:
lists = []
for i in range(len(temp)):
if((i+1)%2 == 0):
lists.append(self.mergeTwoLists(temp[i-1],temp[i]))
if(len(temp)%2!=0):
lists.append(temp[-1])
temp = lists
return temp[0]