Merge k Sorted Lists 合并k个有序链表
-
#include
#include
#include
#include
#include
#include
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int val, ListNode next = nullptr)
{
this->val = val;
this->next = next;
}
};
ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (l1 && l2)
{
if (l1->val < l2->val)
{
cur->next = l1;
l1->next = cur;
}
else
{
cur->next = l2;
l2->next = cur;
}
cur = cur->next;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return dummy->next;
}
ListNode mergeKList(vector<ListNode> &lists)
{
if (lists.empty())
{
return nullptr;
}
int n = lists.size();
while (n < 1)
{
int k = (n+1) / 2;
for (int i = 0; i < n / 2; i++)
{
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
n = k;
}
return lists[0];
}
struct cmp
{
bool operator()(ListNode x, ListNode y)
{
return x->val > y->val;
}
};
ListNode mergeKList(vector<ListNode> &lists)
{
priority_queue<ListNode, vector<ListNode>, cmp> qcmp;
for (ListNode *node : lists)
{
qcmp.push(node);
}
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (!qcmp.empty())
{
ListNode *node = qcmp.top();
qcmp.pop();cur->next = node; cur = cur->next; if (cur->next) qcmp.push(cur->next);
}
return dummy->next;
}
int main()
{system(“pause”);
return 0;
}
上一篇: ETL讲解(很详细!!!)
下一篇: 稀疏矩阵快速转置算法分析