Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
写cmp的时候,第一反应居然是去特例化一个greater,然后发现编译通过不,不能修改greater,然后自己写一个functor,结果忘了是继承binary_function还是binary_predicate,编译后才发觉根本没有binary_predicate这个东西。
写这个CMP是为了堆操作的时候方便比较,结果其实因为对泛型不算很熟悉,浪费的时间可能会更多一些,不过既然是练习,肯定是这样收获大一些。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#define LN ListNode
struct cmp:public binary_function<LN*,LN*,bool>
{
bool operator()(const LN* l1,const LN* l2)
{
if ( !l1 || !l2)
return l1==NULL;
return l1->val>l2->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if ( lists.empty())
return NULL;
LN* head=new LN(-1);
LN* tail=head;
do
{
make_heap(lists.begin(),lists.end(),cmp());
pop_heap(lists.begin(),lists.end());
LN* last=lists.back();
tail->next=last;
tail=last;
if ( last == NULL)
break;
lists.pop_back();
lists.push_back(last->next);
push_heap(lists.begin(),lists.end());
}while(1);
LN* ans=head->next;
delete head;
return ans;
}
};
弄复杂了,没必要自己来做heap的操作的,直接用priority_queue就好了。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class ListNodeCompare:public binary_function<ListNode*,ListNode*,bool>
{
public:
bool operator()(ListNode* t1,ListNode* t2)const
{
if ( !t1||!t2 )
return !t2;
return t1->val>t2->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (lists.empty())
return NULL;
priority_queue<ListNode*,vector<ListNode*>,ListNodeCompare> Q;
for(int i=0;i<lists.size();i++)
if ( lists[i]!=NULL)
Q.push(lists[i]);
ListNode guard(-1);
ListNode* tail=&guard;
while(!Q.empty())
{
ListNode* toAdd=Q.top();
Q.pop();
tail->next=toAdd;
tail=tail->next;
if (toAdd->next)
Q.push(toAdd->next);
}
return guard.next;
}
};