返回

[Leetcode]23. Merge k Sorted Lists(C++)

题目描述

题目链接: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.

例子

例子 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

例子 2

Input: lists = [] Output: []

例子 3

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

Follow Up

Note

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.

解题思路

这道题是 [Leetcode]21. Merge Two Sorted Lists(C++) 的进阶版,要求从合并两个链表变成合并 K 个链表。简单的思路是跟合并两个链表一样,每一次遍历 K 个链表然后取最小的节点进行连接然后进行下一次遍历,这样做的时间复杂度是 O(KN),(每次最多遍历 K 个节点,一共需要遍历 N 次获得 N 个节点,实际上因为链表不等长,所以有一部分链表可能在遍历过程中就结束了)。在 K 的数量级很高时有可能会超时,这里耗时的部分主要是每次遍历 K 个节点时相当于做了一次暴力比较,如果我们能在排列 K 个节点就做好排序的话就可以节省相当时间,这里可以想到用优先队列来存储节点,插入节点为 O(logK),可以降低时间复杂度。代码如下:

/**
 * 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) {}
 * };
 */
#include <queue>

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        std::priority_queue<ListNode*, std::vector<ListNode*>, ListNodeComprare>
            pq;

        for (const auto& node : lists) {
            if (node) {
                pq.push(node);
            }
        }

        ListNode* dummy = new ListNode();
        ListNode* curr = dummy;
        while (pq.size()) {
            ListNode* top = pq.top();
            pq.pop();
            curr->next = top;
            curr = curr->next;
            if (top->next) {
                pq.push(top->next);
            }
        }

        return dummy->next;
    }

private:
    struct ListNodeComprare {
        bool operator()(const ListNode* lhs, const ListNode* rhs) {
            return lhs->val > rhs->val;
        }
    };
};
  • 时间复杂度: O(nlogk)
  • 空间复杂度: O(k)

GitHub 代码同步地址: 23.MergeKSortedLists.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy