Description:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
归并k个链表排序
Solution:
题目类似于上题,但是此题把k不限于为2,这时就不能直接利用归并排序的思想。
因此,此题应该采用堆的思想:
1、将每个非空链表的链头加入最小堆中
2、从堆中取出最小的节点,并在堆中删除,并将next节点放入最小堆中(如果有next)
3、重复2步骤,直至堆空为止。
堆可以采用set或者priority_queue的STL
参照用multiset/priority_Queue来实现最大最小堆
Code:
class Solution {
public:
typedef pair<ListNode*,int> fun;//the second represents which link the node belongs to
struct cmp
{
bool operator()(const fun& a,const fun& b)
{
return (a.first)->val < (b.first)->val;
}
};//redefind the compare function
ListNode* mergeKLists(vector<ListNode*>& lists) {
multiset<fun,cmp> se;
int len=lists.size();
for(int i=0;i<len;++i)
{
if(lists[i])
{
se.insert(make_pair(lists[i],i));
lists[i]=lists[i]->next;
}
}//insert the head node of each link which is not empty
ListNode* pre=NULL;
bool flag=false;
ListNode* root=NULL;
while(!se.empty())
{
fun temp=*(se.begin());//get the head of heap
ListNode* listtemp=new ListNode((temp.first)->val);
if(pre)
pre->next=listtemp;
if(lists[temp.second])
{
se.insert(make_pair(lists[temp.second],temp.second));
lists[temp.second]=lists[temp.second]->next;
}
se.erase(se.begin());
pre=listtemp;
if(!flag)
{
flag=true;
root=pre;
}
}
return root;
}
};