算法设计与分析(16)
题目:Merge k Sorted Lists
问题描述:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
}
};
算法思路:
题目的要求是把k条有序的链表合成一条链表。这里为了考虑到尽量低的复杂度,我们需要用到一些数据结构作为辅助。
(1)首先,我们已经有k条有序的链表。那么为了把其合成一条链表,每次我们都需要从k条链表中取出其中最大的一个节点,然后放入新的链表尾部。所以这里为避免多次比较找最大节点,我们就应该想到使用大根堆的数据结构。生成大小为n的大根堆的用时为O(n),每次取出和放入的用时为O(log2 n)。
(2)使用大根堆的数据结构,在STL中,我们就可以考虑直接使用优先队列(priority_queue)了。为此,我们需要引入比较函数:
struct compare
{
bool operator()(const ListNode* l1, const ListNode* l2)
{
if (l1 == NULL || l2 == NULL)
return true;
return l1->val > l2->val;
}
};
(3)当我们把k条链表的头部放入优先队列(priority_queue)中,就可以直接使用top()操作把最大的节点取出来。然后把取出来的节点它的下一个节点放如优先队列(priority_queue)中。因为k条链表是有序的,所以这种算法能够保证每次从优先队列(priority_queue)取出来的节点都是当前最大的节点。因此,我们确保使用优先队列(priority_queue)正确性。
(4)在具体操作:
a)首先初始化优先队列(priority_queue),这里需要保证优先队列(priority_queue)中的指针不为NULL:
priority_queue<ListNode*, vector<ListNode*>, compare> pque;
for (int i = 0; i < lists.size(); ++i)
if (lists[i] != NULL)
pque.push(lists[i]);
b) 若初始化优先队列(priority_queue)为空,直接返回空指针:
if (pque.empty())
return NULL;
c)我们只用三个指针分别指向新链表的头部、尾部,以及从pque中取出来的节点,并初始化他们:
ListNode *tail, *head, *node;
head = pque.top();
pque.pop();
tail = head;
node = tail;
d)最后通过判断pque为空来判断算法是否结束。若不为空且node的下一个节点不为空,可以将其放入pque中。然后继续从pque中取出最节点,放入新链表的尾部,如此循环:
while (!pque.empty())
{
if (node->next != NULL)
pque.push(node->next);
node = pque.top();
pque.pop();
tail->next = node;
tail = tail->next;
}
e)最后返回新链表的头部head。
程序运行结果:
结果说明了程序的高效。
实现代码
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct compare
{
bool operator()(const ListNode* l1, const ListNode* l2)
{
return l1->val > l2->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists)
{
priority_queue<ListNode*, vector<ListNode*>, compare> pque;
for (int i = 0; i < lists.size(); ++i)
if (lists[i] != NULL)
pque.push(lists[i]);
ListNode *tail, *head, *node;
if (pque.empty())
return NULL;
head = pque.top();
tail = head;
node = tail;
pque.pop();
while (!pque.empty())
{
if (node->next != NULL)
pque.push(node->next);
node = pque.top();
pque.pop();
tail->next = node;
tail = tail->next;
}
return head;
}
int main()
{
ListNode *l1 = NULL, *l2 = NULL;
vector<ListNode*> lists;
lists.push_back(l1);
lists.push_back(l2);
ListNode* res = mergeKLists(lists);
return 0;
}