题意:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题解:建立一个大小为k的最小堆,即堆顶存放最小元素,因为k个链表已排好序,借鉴归并排序的技巧,先取出堆顶的元素,再放入堆顶元素所在链表的表头的元素,再维持最小堆循环迭代。
注意直接链表存入会导致逆序,可以先存入vector,再逆序存入链表。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int insertNode(ListNode** head,int val)
{
ListNode* newNode = new ListNode(val);
newNode->next = *head;
*head = newNode;
return 0;
}
class qNode{
public:
int val;
int index;
friend bool operator<(qNode a,qNode b){
return a.val > b.val;
//val小的优先级高,先从queue pop出来
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<qNode> q;
vector<int> tmp;
qNode now,next;
ListNode* head = NULL;
for(int i = 0;i < lists.size();i++){
if(lists[i] != NULL){
now.val = lists[i]->val;
lists[i] = lists[i]->next;
now.index = i;
q.push(now);
}
}
while(!q.empty()){
now = q.top();
q.pop();
tmp.push_back(now.val);
if(lists[now.index] != NULL){
next.val = lists[now.index]->val;
next.index = now.index;
q.push(next);
lists[now.index] = lists[now.index]->next;
}
}
for(int i = tmp.size()-1;i >= 0;i--)
{
insertNode(&head,tmp[i]);
}
return head;
}
};