23. Merge k Sorted Lists

Hard (Khó) C++ Python 🔗 Xem trên LeetCode

📋 Đề Bài

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

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

 

Constraints:

  • k == lists.length
  • 0 <= k <= 104
  • 0 <= lists[i].length <= 500
  • -104 <= lists[i][j] <= 104
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length will not exceed 104.

🧠 Thuật Toán & Kỹ Thuật

Linked List (Danh sách liên kết)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0023-merge-k-sorted-lists.cpp
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    ListNode *merge(ListNode *l1, ListNode *l2) {
        ListNode *l3 = new ListNode(0);
        ListNode *cr = l3;
        while (l1 and l2) {
            if (l1->val < l2->val) {
                cr->next = new ListNode(l1->val);
                l1 = l1->next;
            } else {
                cr->next = new ListNode(l2->val);
                l2 = l2->next;
            }
            cr = cr->next;
        }
        cr->next = l1 ? l1 : l2;
        return l3->next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.empty()) {
            return nullptr;
        }
        int len = lists.size();
        while (len > 1) {
            for (int i = 0; i < len / 2; ++i) {
                lists[i] = merge(lists[i], lists[len - 1 - i]);
            }
            len = (len + 1) / 2;
        }
        return lists.front();
    }
};
Python 0023-merge-k-sorted-lists.py
# 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[Optional[ListNode]]) -> Optional[ListNode]:
        n = len(lists)

        if n == 0:
            return None
        
        if n == 1:
            return lists[0]
        
        def merge(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
            list3 = ListNode(0)
            currNode = list3
            
            while list1 and list2:
                if list1.val <= list2.val:
                    currNode.next = ListNode(list1.val)
                    list1 = list1.next
                else:
                    currNode.next = ListNode(list2.val)
                    list2 = list2.next
                currNode = currNode.next
                
            while list1:
                currNode.next = ListNode(list1.val)
                list1 = list1.next
                currNode = currNode.next
            
            while list2:
                currNode.next = ListNode(list2.val)
                list2 = list2.next
                currNode = currNode.next
                
            return list3.next
        
        while len(lists) > 1:
            lists.append(merge(lists[0], lists[1]))
            lists.remove(lists[0])
            lists.remove(lists[0])
            
        return lists[0]