Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 23. Merge k Sorted Lists

Rain Hu

23. Merge k Sorted Lists


一、題目

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:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Heap (Priority Queue)

ListNode* mergeKLists(vector<ListNode*>& lists) {
    auto comp = [](const auto& a, const auto& b) {return a->val > b->val;};     // min heap 的寫法跟 sort 相反
    priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp);
    ListNode* dummy = new ListNode(-1);     // 建立 dummy head
    ListNode* curr = dummy;
    for (const auto& list : lists) {
        if (list) pq.push(list);            // 排除空鏈表
    }
    while (!pq.empty()) {
        curr->next = pq.top();
        pq.pop();
        if (curr->next->next) pq.push(curr->next->next);    // 若鏈表還有 next,繼續加入 min heap
        curr = curr->next;
    }
    
    return dummy->next;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 151. Reverse Words in a String
Next
[LeetCode] 22. Generate Parentheses