1 两两链表合并(超时)
class Solution {
public:
ListNode* merge2Lists(ListNode* l1, ListNode* l2) {
auto prehead = new ListNode();
auto merge = prehead;
while (l1 || l2) {
if (!l1) {
merge->next = l2;
break;
} else if (!l2) {
merge->next = l1;
break;
} else if (l1->val <= l2->val) {
merge->next = new ListNode(l1->val);
l1 = l1->next;
} else if (l1->val > l2->val) {
merge->next = new ListNode(l2->val);
l2 = l2->next;
}
merge = merge->next;
}
return prehead->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty()) return nullptr;
if (lists.size() == 1) return lists[0];
auto mergeList = merge2Lists(lists[0], lists[1]);
for (int i = 2; i < lists.size(); i++)
mergeList = merge2Lists(mergeList, lists[i]);
return mergeList;
}
};
2 将K个链表首个节点依次压入小根堆,然后逐个弹出
class cmp {
public:
bool operator()(const ListNode* a, const ListNode* b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
auto reshead = new ListNode();
auto node = reshead;
for (auto& head : lists)
if (head) q.push(head);
while (!q.empty()) {
auto tmp = q.top(); q.pop();
if (tmp->next) q.push(tmp->next);
node->next = tmp;
node = node->next;
}
return reshead->next;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4db7e2d50d38417015695c09a8d376d0.png)