題目描述:
合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。
示例:輸入:
[1->4->5,
1->3->4,
2->6
]輸出: 1->1->2->3->4->4->5->6
# definition for singly-linked list.
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
:def
mergeklists
(self, lists: list[listnode])-
> listnode:
result =
for i in lists:
while i :
i = i.
next
if result ==
:return
result.sort(
) line1 = listnode(0)
line2 = line1
while result:
line1.
next
= listnode(result.pop(0)
) line1 = line1.
next
return line2.
next
執行結果1:
參考程式2:
# definition for singly-linked list.
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
:def
mergeklists
(self, lists: list[listnode])-
> listnode:
if lists is
none
orlen
(lists)==0
:return
none
while
len(lists)
>1:
temp =
for i in
range(0
,len
(lists)-1
,2):
p = self.mergetwolist(lists[i]
, lists[i +1]
)iflen(lists)%2
==1:-
1]) lists = temp
return lists[0]
defmergetwolist
(self, line1, line2)
:if line1 is
none
:return line2
if line2 is
none
:return line1
result = listnode(0)
r = result
while line1 is
notnone
and line2 is
notnone
:if line1.val <= line2.val:
r.next
= line1
line1 = line1.
next
else
: r.
next
= line2
line2 = line2.
next
r = r.
next
if line1 is
notnone
: r.
next
= line1
if line2 is
notnone
: r.
next
= line2
return result.
next
執行結果2:
參考程式3:
# definition for singly-linked list.
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class
solution
:def
mergeklists
(self, lists: list[listnode])-
> listnode:
import heapq
result = listnode(-1
) r = result
line =
list()
temp =
0for i in lists:
while i:
(i.val, temp, i)
) i = i.
next
temp +=
1while line:
r.next[2
] r = r.
next
return result.
next
力扣 23 合併K個排序鍊錶 Golang
知識點 鍊錶 難度 困難 題目 合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。示例 輸入 1 4 5,1 3 4,2 6 輸出 1 1 2 3 4 4 5 6 方法 分治 merge 對兩個有序鍊錶進行歸併排序 func merge left listnode,right ...
力扣LeetCode 23 合併K個排序鍊錶
合併 k 個排序鍊錶,返回合併後的排序鍊錶。請分析和描述演算法的複雜度。示例 輸入 1 4 5,1 3 4,2 6 輸出 1 1 2 3 4 4 5 6 比較好的兩種思路 1 與合併兩個有序鍊錶一樣,k個鍊錶一起從頭往尾走,每次選取k個鍊錶中指標指向位置的最小值,這個最小值使用優先佇列維護較為合適。...
合併k個排序鍊錶
合併k個排序鍊錶,並且返回合併後的排序鍊錶。嘗試分析和描述其複雜度。樣例 給出3個排序鍊錶 2 4 null,null,1 null 返回 1 2 4 null 兩兩合併 合併ab得到c 合併cd得到e definition for listnode.public class listnode pu...