Posted on 2023-03-12 16:09
Uriel 閱讀(48)
評論(0) 編輯 收藏 引用 所屬分類:
數據結構 、
閑來無事重切Leet Code 、
排序
給出若干已排序的單鏈表,合并成一個
先遍歷每個單鏈表,記錄所有數字之后從大到小sort,之后一個個塞入鏈表,最后返回頭指針
沒想到可以Beat 100% Python submissions。。。
1 #23
2 #Runtime: 53 ms (Beats 100%)
3 #Memory: 22.3 MB (Beats 26.72%)
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def mergeKLists(self, lists):
12 """
13 :type lists: List[ListNode]
14 :rtype: ListNode
15 """
16 total = []
17 for i in lists:
18 h = i
19 while h:
20 total.append(h.val)
21 h = h.next
22 total = sorted(total, reverse = True)
23 head = None
24 for i in total:
25 head = ListNode(i, head)
26 return head