题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 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 = []
输出:[]
解题思路
- 采用归并排序(分治策略)的思想
仔细一看,其实该题就是归并排序的并过程,我们来回顾一下归并排序的过程,如下图(来源其他人的CSDN):
相当于不断的两两合并,最终再次两两合并,其中两两合并可以参考合并两个有序链表,时间复杂度为O(m+n),采用分治策略,整体时间复杂度为:O(n∗log(k)),代码如下:
/**
* 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* mergeTwo(ListNode* list1, ListNode* list2 = NULL) {
if(list1==NULL)
return list2;
if(list2==NULL)
return list1;
if(list1->val < list2->val){
list1->next = mergeTwo(list1->next,list2);
return list1;
}else{
list2->next = mergeTwo(list1,list2->next);
return list2;
}
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int length = lists.size();
if (length == 0)
return NULL;
if (length == 1)
return lists[0];
int pivot = length / 2;
vector<ListNode*> a(lists.begin(), lists.begin() + pivot);
vector<ListNode*> b(lists.begin()+pivot, lists.end());
ListNode* tmp1 = mergeKLists(a);
ListNode* tmp2 = mergeKLists(b);
return mergeTwo(tmp1, tmp2);
}
};
- 采用K路归并的思想,利用优先队列
```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:
struct cmp
{
bool operator()(ListNode* a,ListNode* b)
{
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp > que;
for (auto node : lists)
if (node)
que.push(node);
ListNode head;
ListNode* tail = &head;
while (!que.empty()) {
ListNode* top_node = que.top();
que.pop();
tail->next = top_node;
tail = tail->next;
if (top_node->next)
que.push(top_node->next);
}
return head.next;
}
}; ```
