Leetcode: 23. Merge k Sorted Lists
Description
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路
- 使用一个优先级队列保存每个链表当前元素值,然后每次取出最小的,将其后的另一个加入队列
代码
- 时间复杂度。每一个链表平均长度为k,一共有m个链表
- 最开始建立最小堆的时间为O(mlgm)
- 然后找的时间:O(mk)*O(lgm),查找时间和调整堆的时间
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp{
bool operator()(const ListNode* a, const ListNode *b){ return a->val > b->val; }
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head = NULL, *ptr = NULL, *tmp = NULL;
priority_queue<ListNode*, vector<ListNode*>, cmp> Queue;
for(int i = 0; i < lists.size(); ++i){
if(lists[i])
Queue.push(lists[i]);
}
while(!Queue.empty()){
tmp = Queue.top();
Queue.pop();
if(tmp->next)
Queue.push(tmp->next);
if(!head){
head = ptr = tmp;
}
else{
ptr->next = tmp;
ptr = ptr->next;
}
}
return head;
}
};