原题:
合并 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:先处理相邻的两个链表,使用的解法和第21题一样
思路:直接将数组中的各个链表两两相加。
** 超时**
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergetowlist(self,temp1,temp2):
if temp1 and temp2:
if temp1.val > temp2.val:
temp1 , temp2 = temp2, temp1
temp1.next = self.mergetowlist(temp1.next,temp2)
return temp1 or temp2
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if lists == []:
return None
while len(lists) !=1:
temp1= lists[0]
temp2 = lists[1]
lists[0] = self.mergetowlist(temp1,temp2)
lists.pop(1)
return lists[0]
解法二: 暴力法
先将数组中各个节点的val值提取出来放入到一个数组中,在将数组进行排序,并创建一个新的链表。
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
nodes = []
head = point = ListNode(0)
for l in lists:
while l:
nodes.append(l.val)
l = l.next
for x in sorted(nodes):
point.next = ListNode(x)
point = point.next
return head.next
解法三 :(优先队列)
思路:使用优先队列存储数组的每个链表的首节点,获得最小值的节点,将这个节点接在point这个最终有序链表的后面。
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = point = ListNode(0)
q = PriorityQueue() # 创建优先队列
for l in lists:
if l:
q.put((l.val, l)) # 根据l.val值进行排序
while not q.empty():
val, node = q.get() # 出队
point.next = ListNode(val)
point = point.next
node = node.next
if node:
q.put((node.val, node)) # 如果node存在,则将这个节点加入到队列中去
return head.next
解法四:分治法
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount - interval, interval * 2):
lists[i] = self.mergetowlist(lists[i], lists[i + interval])
interval *= 2
return lists[0] if amount > 0 else None
def mergetowlist(self,temp1,temp2):
if temp1 and temp2:
if temp1.val > temp2.val:
temp1 , temp2 = temp2, temp1
temp1.next = self.mergetowlist(temp1.next,temp2)
return temp1 or temp2