Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题意:合并k个排序数组(升序排列)
1、递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) return nullptr;
while (lists.size() > 1) {
lists.push_back(mergeTwoLists(lists[0], lists[1]));//每次将列表中前两个数组合并,放到列表尾,然后删除列表中前两个元素
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
//合并两个数组
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) return l2;
if (l2 == nullptr) return l1;
if (l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
2、堆
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
static bool heapComp(ListNode *a, ListNode *b) {
return a->val > b->val;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode head(0);
ListNode *curNode = &head;
vector<ListNode*> v;
for (int i = 0; i < lists.size(); ++i)
if (lists[i]) v.push_back(lists[i]);
make_heap(v.begin(), v.end(), heapComp);//建堆
while (v.size() > 0) {
curNode->next = v.front();
pop_heap(v.begin(), v.end(), heapComp);
v.pop_back();
curNode = curNode->next;
if (curNode->next) {
v.push_back(curNode->next);
push_heap(v.begin(), v.end(), heapComp);
}
}
return head.next;
}
};