原題:
合併 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