1. 题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
2. 代码实现
方法1:逐一两两合并链表:
执行用时 :5792 ms, 在所有 Python 提交中击败了5.03%的用户
内存消耗 :18.4 MB, 在所有 Python 提交中击败了56.25%的用户
# 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
"""
lens = len(lists)
if lens==0:
return lists
else:
while lens>=2:
# 将前两个链表和并后赋值给原lists[1]位置
lists[1] = self.merge2List(lists[0], lists[1])
# 去除原lists第一个链表后为新的lists
lists = lists[1:]
lens -= 1
return lists[0]
# 合并两个链表的函数
def merge2List(self, list1, list2):
LiNo = ListNode(-1)
current = LiNo
while list1 and list2:
if list1.val>=list2.val:
current.next = list2
current = current.next
list2 = list2.next
else:
current.next = list1
current = current.next
list1 = list1.next
if list1:
current.next = list1
else:
current.next = list2
return LiNo.next
复杂度分析:
时间复杂度: O(kN),其中k 是链表的数目。
我们可以在 O(n) 的时间内合并两个有序链表,其中 n 是两个链表的总长度。
空间复杂度:O(1)。
我们可以在 O(1)空间内合并两个有序链表。
方法2:暴力法
遍历所有链表,将所有节点的值放到一个数组中。将这个数组排序,然后遍历所有元素得到正确顺序的值。用遍历得到的值,创建一个新的有序链表。
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
self.nodes = []
head = point = ListNode(0)
# 获得所有节点的值
for l in lists:
while l:
self.nodes.append(l.val)
l = l.next
# sorted()返回升序
for x in sorted(self.nodes):
point.next = ListNode(x)
point = point.next
return head.next