Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
方法1:使用最小堆
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp {
bool operator()(ListNode *p1, ListNode *p2) {
return p1->val > p2->val;
}
};
class Solution {
public:
//时间复杂度为O(nlgk),n为所有链表总的节点数,k为链表个数
ListNode *mergeKLists(vector<ListNode *> &lists) {
//建立最小堆,堆的大小为链表个数k
priority_queue < ListNode*, vector<ListNode*>, cmp> Q;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL)
Q.push(lists[i]);
}
ListNode *dummy = new ListNode(-1);
dummy->next = NULL;
ListNode *tail = dummy;
while (!Q.empty()) {
ListNode *add = Q.top();
Q.pop();
tail->next = add;
tail = tail->next;
if (add->next)
Q.push(add->next);
}
return dummy->next;
}
};
方法2:使用归并,将所有链表两两归并排序,直到只剩一个链表,时间复杂度与方法1相同。