iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
0

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Example 1: <-- 兩個以上的 MergeSort
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:
Input: lists = []
Output: []

Example 3:
Input: lists = [[]]
Output: []

Constraints:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] is sorted in ascending order.
The sum of lists[i].length won't exceed 10^4.


思路
Step 0:將 每個 ListNode 拿出 統一塞進 新的list,
Step 1:新的list 排序 is sorted(新的list) not 新的list.sort()
Ref : https://stackoverflow.com/questions/7301110/why-does-return-list-sort-return-none-not-the-list
Step 2:新的list 轉 ListNode by ListNode(添加的值)
Other
Ref : LeetCode 23. Merge k Sorted Lists - Python思路總結

正解 待改進 to be enhance ...

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        tmpList = []
        for listE in lists:
            while listE!=None:
                print(listE.val)
                tmpList.append(listE.val)
                listE = listE.next
            
        print(tmpList)
        # sort it 
        #print(tmpList.sort())
        #for i in tmpList.sort():
            #print(i)
                
        print(sorted(tmpList))
        dummyNode = ListNode()
        head = dummyNode
        for j in sorted(tmpList):
            dummyNode.next = ListNode(j)
            dummyNode = dummyNode.next
        print(head.next)
        return head.next

Result
時間&空間 皆慘不忍睹 QQ
所以 留下 另解 TODO !!!


上一篇
(Medium) 22. Generate Parentheses
下一篇
(Medium) 24. Swap Nodes in Pairs
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言