iT邦幫忙

2022 iThome 鐵人賽

DAY 30
0
自我挑戰組

LeetCode Top 100 Liked系列 第 30

[Day 30] Merge k Sorted Lists (Hard)

  • 分享至 

  • xImage
  •  

23. Merge k Sorted Lists

Question

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

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

Solution 1: Priority Queue (Different ListNode)

from queue import PriorityQueue

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        q = PriorityQueue()
        for headOfK in lists:
            cur = headOfK
            while cur:
                q.put(cur.val)
                cur = cur.next
                
        dummy = ListNode()        
        cur = dummy
        while q.qsize():
            node = q.get()
            cur.next = ListNode(node)
            cur = cur.next
        return dummy.next

Time Complexity: O(N*Log(N))
Space Complexity: O(N)

Solution 2: Priority Queue (Same ListNode)

Time Complexity: O(N*Log(N))
Space Complexity: O(N)

Reference

Follow-up: Merge Two Sorted Lists


上一篇
[Day 29] Roman to Integer (Easy)
下一篇
[Day 31] Letter Combinations of a Phone Number (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言