23. 合并 K 个升序链表
一句话套路小顶堆按值合并 k 路 / 分治
题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
示例 2:
输入:lists = [] 输出:[]
示例 3:
输入:lists = [[]] 输出:[]
提示:
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4lists[i]按 升序 排列lists[i].length的总和不超过10^4
思路
时间
O(N log k)空间
O(k)。对比「逐个两两合并」是 O(N·k)思路
最小堆维护「每条链当前未合并的最小结点」。弹出接答案,把它 next 入堆。
C++ 细节
priority_queue 默认是最大堆,比较器写 a->val > b->val 才得到最小堆。
图解
链表结构(来自本仓库测试数据)
C++17 题解
namespace lc0023 {
class Solution {
public:
struct Cmp {
bool operator()(const ListNode* a, const ListNode* b) const {
return a->val > b->val; // 注意:> 才是小顶堆
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, Cmp> pq;
for (ListNode* l : lists)
if (l) pq.push(l);
ListNode dummy(0);
ListNode* tail = &dummy;
while (!pq.empty()) {
ListNode* node = pq.top();
pq.pop();
tail->next = node;
tail = node;
if (node->next) pq.push(node->next);
}
tail->next = nullptr;
return dummy.next;
}
};
}
单元测试
以下用例都在本仓库里实际编译运行过,图解里的数据也取自这里。
lc0023::Solution s;
vector<ListNode*> lists{buildList({1, 4, 5}), buildList({1, 3, 4}), buildList({2, 6})};
CHECK_EQ(listToVec(s.mergeKLists(lists)), vector<int>{1, 1, 2, 3, 4, 4, 5, 6});
vector<ListNode*> noLists{};
CHECK_TRUE(s.mergeKLists(noLists) == nullptr);
vector<ListNode*> onlyNull{nullptr, nullptr};
CHECK_TRUE(s.mergeKLists(onlyNull) == nullptr);