合并K个排序链表
思路:
暴力合并为一个链表后sort(误!)
插堆还原(误!)
每次选一个最小的插入(堆优化选择过程) 复杂度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct rnode
{
ListNode *it;
bool operator < (const rnode b) const
{
return -it->val < -b.it->val;
}
};
ListNode* mergeKLists(vector<ListNode*> &lists) {
priority_queue <rnode> Q;
ListNode *head = new ListNode(0);
ListNode *it = head;
for(auto x : lists)
{
if(x != NULL)
{
Q.push(rnode{x});
}
}
while(!Q.empty())
{
auto now = Q.top();
Q.pop();
it->next = now.it;
it = it->next;
if(now.it->next != NULL)
{
Q.push(rnode{now.it->next});
}
}
return head->next;
}
};
两两合并直到只剩一个(递归)复杂度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *merge(ListNode *a, ListNode *b)
{
ListNode *ret = new ListNode(0);
ListNode *now = ret;
while(a != NULL && b != NULL)
{
if(a->val <= b->val)
{
now->next = a;
a = a->next;
now = now->next;
}
else
{
now->next = b;
b = b->next;
now = now->next;
}
}
while(a != NULL)
{
now->next = a;
a = a->next;
now = now->next;
}
while(b != NULL)
{
now->next = b;
b = b->next;
now = now->next;
}
return ret->next;
}
ListNode* mergeKLists(vector<ListNode*> &lists) {
while(lists.size() >= 2)
{
vector <ListNode*> ret;
for(int i = 0; i < lists.size(); i += 2)
{
if(i != lists.size() - 1)
{
ret.push_back(merge(lists[i], lists[i + 1]));
}
else
{
ret.push_back(lists[i]);
}
}
lists = ret;
}
return lists.size() ? lists[0] : NULL;
}
};
Done!