leetcode 合併k個排序列表(三種解法)
阿新 • • 發佈:2019-01-14
題目描述
合併 k 個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度。
解法1
建立一個數組,將所有元素儲存,排序之後,再連結成一個連結串列
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
#遍歷連結串列,將所有連結串列的所有元素放到一個數組裡面
nodeList = []
for i in range(len(lists)):
currentNode = lists[i]
#遍歷某個連結串列
while(currentNode):
nodeList.append(currentNode)
currentNode = currentNode.next
#根據node的val對陣列進行排序
nodeList = sorted(nodeList,key = lambda x: x.val)
#對排序好的陣列的元素,一個個地連線成新的連結串列(這裡的tempHead是為了方便設定的頭節點)
tempHead = ListNode(0)
currentNode = tempHead
for i in range(len(nodeList)):
currentNode.next = nodeList[i]
currentNode = currentNode.next
return tempHead.next
解法2
對lists裡面的連結串列兩兩合併,知道lists裡面只有一個元素
class Solution:
def mergeTowLists(self, list1, list2):
head = None
if list1 == None and list2 == None:
return None
if list1 == None:
return list2
if list2 == None:
return list1
if list1.val <= list2.val:
head = list1
head.next = self.mergeTowLists(list1.next, list2)
else:
head = list2
head.next = self.mergeTowLists(list, list2.next)
return head
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if lists == []:
return None
while len(lists) > 1:
list1 = lists.pop()
list2 = lists.pop()
lists.append(self.mergeTowLists(list1, list2))
return lists[0]
這種解法是超時的:
解法3
還是使用兩兩排序的方式,不過採用分治法的思想。
定義一個partition函式,進行二分歸併。
注意partition函式的寫法
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTowLists(self, list1, list2):
head = None
if list1 == None and list2 == None:
return None
if list1 == None:
return list2
if list2 == None:
return list1
if list1.val <= list2.val:
head = list1
head.next = self.mergeTowLists(list1.next, list2)
else:
head = list2
head.next = self.mergeTowLists(list1, list2.next)
return head
def partition(self, lists, start, end):
if start == end:
return lists[start]
if start < end:
mid = (start + end) // 2
l1 = self.partition(lists, start, mid)
l2 = self.partition(lists, mid + 1, end)
return self.mergeTowLists(l1, l2)
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if lists == []:
return None
return self.partition(lists, 0, len(lists) - 1)
這種方法的效率要比第一種方法小點