題目描述:
合并 k 個排序鏈表,返回合并后的排序鏈表。請分析和描述算法的復雜度。
示例:
輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6
我的方法:
可以用遞歸或者直接循環,將k個排序鏈表轉換為2個鏈表的排序。假如用遞歸的方法:
- 對于輸入lists而言,可以將其轉換為list[0]和slef.mergeKLists(lists[1:])。
- 終止條件是len(lists)為1。
但是遞歸的耗時太長,用以下方法會超時。時間復雜度為len(lists)len(ListNode)2,感覺還好啊。
# 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
"""
# 遞歸解法
if len(lists)>1:
tmp0=lists[0]
tmp1=self.mergeKLists(lists[1:])
ans=ListNode(0)
head=ans
while tmp0 and tmp1:
if tmp0.val<=tmp1.val:
ans.next=tmp0
tmp0=tmp0.next
else:
ans.next=tmp1
tmp1=tmp1.next
ans=ans.next
ans.next=tmp0 if tmp0 else tmp1
return head.next
# 終止條件:考慮lists只有一個元素或為空的情況
elif len(lists)==1:
return lists[0]
else:
return ListNode(0).next
如果直接用循環來解決呢?基本思路如下:
- 記錄當前已經完成合并排序的鏈表l。
- 對于lists中的每一個鏈表,將其與鏈表l合并排序,排序方法同兩個有序鏈表的合并。
- 直至循環完成。
循環的速度要快一點:執行用時 : 7268 ms, 在Merge k Sorted Lists的Python提交中擊敗了4.07% 的用戶。內存消耗 : 17.4 MB, 在Merge k Sorted Lists的Python提交中擊敗了39.18% 的用戶。但還是很慢。
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# 結果鏈表
ans=ListNode(None)
head=ans
# 循環兩兩排序和整合
for l in lists:
tmp=ListNode(0)
tmp_head=tmp
while ans and l:
if ans.val<=l.val:
tmp.next=ans
ans=ans.next
else:
tmp.next=l
l=l.next
tmp=tmp.next
tmp.next=ans if ans else l
ans=tmp_head.next
return head.next
別人的解法:
直接將多個ListNode的排序轉換為數組的排序,就快了很多。省去了大量的比較操作。排名雖然不算靠前,但耗時降低明顯:執行用時 : 120 ms, 在Merge k Sorted Lists的Python提交中擊敗了41.86% 的用戶。內存消耗 : 17.4 MB, 在Merge k Sorted Lists的Python提交中擊敗了39.18% 的用戶。
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# 將多個數組整合為1個數組
node_list=[]
for i in lists:
while i:
node_list.append(i)
i=i.next
# 對單個數組排序
node_list.sort(key=lambda x:x.val)
ans=ListNode(0)
head=ans
# 數組轉換為鏈表
for i in node_list:
ans.next=i
ans=ans.next
return head.next