23.Merge k Sorted Lists
题目: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析: 这是一道很基本的题, 可以用有限队列, 分治法等解决.
优先队列: C++ STL中有提供优先队列priority_queue
, 是一模板, 声明如下:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
注意默认的比较策略(policy)是std::less
, 此处需要我们提供自己的比较函数, 只需定义一个仿函数(functor), 也即重载operator()运算符:
struct cmp {
bool operator()(ListNode* p, ListNode* q) {
return p->val > q->val;
}
};
priority_queue的大小始终为k, 每次一个ListNode经过优先队列时调整的复杂度为O(lgk), 节点插入链表的复杂度为O(1), 共有nk个节点, 故算法复杂度为O(nklgk), 空间复杂度为O(k).整个代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp {
bool operator()(ListNode* p, ListNode* q) {
return p->val > q->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> p_queue;
ListNode* dummy = new ListNode(0), *tail = dummy;
for(int i = 0; i < lists.size(); ++i) {
if(lists[i]) p_queue.push(lists[i]);
}
while(!p_queue.empty()) {
tail->next = p_queue.top();
tail = tail->next;
p_queue.pop();
if(tail->next)
p_queue.push(tail->next);
}
tail = dummy->next;
delete dummy;
return tail;
}
};
分治法: 每次合并两个链表, 直到只剩一个链表为止. 算法复杂度为O(nklgk), 空间复杂度为O(1).
/**
* 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) {
if(lists.empty()) return NULL;
int end = lists.size() - 1, begin;
while(end > 0) {
begin = 0;
while(begin < end) {
lists[begin] = merge(lists[begin], lists[end]);
begin++, end--;
}
}
return lists[0];
}
ListNode* merge(ListNode* p, ListNode* q) {
if(p == NULL) return q;
if(q == NULL) return p;
ListNode* dummy = new ListNode(0);
ListNode* tail = dummy;
while(p && q) {
if(p->val < q->val) {
tail->next = p;
p = p->next;
}
else {
tail->next = q;
q = q->next;
}
tail = tail->next;
}
tail->next = p ? p : q;
tail = dummy->next;
delete dummy;
return tail;
}
};
网友评论