题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析:合并k个有序链表,其本质就是合并2个有序链表(用递归代码会更简洁),然后作k-1次就可以了。如果每次合并的链表是最短的,那应该时间最短,这个可以用小根堆实现。
/**
* 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)
{
priority_queue<ListNode*, vector<ListNode*>, cmp>pq;
for(auto i:lists)
{
if(i) //这句判断很有必要,不能把空的加入队列。比如这组数据:[[],[]]
{
pq.push(i);
}
}
if(pq.empty())
{
return nullptr;
}
ListNode* ans = pq.top();
pq.pop();
ListNode* tail = ans;
if(tail->next)
{
pq.push(tail->next);
}
while(!pq.empty())
{
tail->next = pq.top();
tail = tail->next;
pq.pop();
if(tail->next)
{
pq.push(tail->next);
}
}
return ans;
}
};
使用递归:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode*l1,ListNode*l2){
//if(l1==NULL&l2==NULL)
// return NULL;
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;
}
}
ListNode *mergeKLists(vector<ListNode*> &lists)
{
if(lists.size()==0)
return NULL;
while(lists.size()>1){
lists.push_back(mergeTwoLists(lists[0],lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists[0];
}
};