合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。
示例:
輸入:[1
->4-
>5,
1->3-
>4,
2->6]
輸出:1
->1-
>2-
>3-
>4-
>4-
>5-
>
6
題目要求合併給定的k個排序鍊錶,k = 0,1, …, n,且每個鍊錶中的元素可能有重複值。
class
solution
(object):
defmergeklists
(self, lists)
:if lists ==
:return
r =for l in lists:
cur = l
while cur:
cur = cur.
next
r =sorted
(r) newhead = listnode(-1
) cur = newhead
for i in r:
cur.
next
= listnode(i)
cur = cur.
next
return newhead.
next
class
solution
:def
mergeklists
(self, lists: list[listnode])-
> listnode:
defmerge
(head1, head2)
: t = listnode(-1
) head = t
while head1 and head2:
if head1.val <= head2.val:
head.
next
= listnode(head1.val)
head1 = head1.
next
else
: head.
next
= listnode(head2.val)
head2 = head2.
next
head = head.
next
if head1: head.
next
= head1
if head2: head.
next
= head2
return t.
next
iflen
(lists)==0
:return
iflen
(lists)==1
:return lists[0]
newhead =
none
for i in
range(0
,len
(lists)-1
):newhead = merge(newhead, lists[i]
)return newhead
乙個比較優的做法是官方解答中給出的分治法:
class
solution
(object):
defmergeklists
(self, lists)
:"""
:type lists: list[listnode]
:rtype: listnode
"""amount =
len(lists)
interval =
1while interval < amount:
for i in
range(0
, amount - interval, interval *2)
: lists[i]
= self.merge2lists(lists[i]
, lists[i + interval]
) interval *=
2return lists[0]
if amount >
0else lists
defmerge2lists
(self, l1, l2)
: head = point = listnode(0)
while l1 and l2:
if l1.val <= l2.val:
point.
next
= l1
l1 = l1.
next
else
: point.
next
= l2
l2 = l1
l1 = point.
next
.next
point = point.
next
ifnot l1:
point.
next
=l2 else
: point.
next
=l1 return head.
next
合併k個排序鍊錶
23 合併K個排序鍊錶
合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。示例 輸入 1 4 5,1 3 4,2 6 輸出 1 1 2 3 4 4 5 6 偷懶直接複製了以前的堆的 所有看上去長了點 class priorityqueue priority是設定優先順序 true為大根堆 false為...
23 合併K個排序鍊錶
合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。採用分治法的思想,將 k 個排序鍊錶先合併為 k 2 個鍊錶。依次迴圈,直至合併為1個鍊錶為止。注意 從 k 到 k 2 時,如何定義索引,將每兩個鍊錶合併,而且必須符合奇數 偶數個鍊錶的情況。解決辦法 k n 1 2 list...
23 合併K個排序鍊錶
合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。示例 輸入 1 4 5,1 3 4,2 6 輸出 1 1 2 3 4 4 5 6 暴力法 將所有的節點放在乙個陣列中,然後對陣列排序,最後遍歷陣列,組建新的鍊錶。definition for singly linked list...