LeetCode 23. Merge k Sorted Lists
Solution1:我的答案
确实很慢啊
/**
* 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) {
int num_nullptr = 0;
for (auto listnode : lists)
if (!listnode) num_nullptr++;
if (num_nullptr == lists.size())
return NULL;
ListNode* new_head = new ListNode(-1), *cur = new_head;
while (num_nullptr < lists.size()) {
num_nullptr = 0;
int index = 0, index_val = INT_MAX;
for (int i = 0; i < lists.size(); i++) {
if (!lists[i]) num_nullptr++;
else {
if (lists[i]->val < index_val) {
index = i;
index_val = lists[index]->val;
}
}
}
if (index_val != INT_MAX) {//为了防止lists中所有元素均为NULL时,进行下面的操作,故要加上判断条件
cur->next = lists[index];
lists[index] = lists[index]->next;
cur = cur->next;
}
}
return new_head->next;
}
};
Solution2:分治
人家想考的应该是这个知识点
参考网址:http://www.cnblogs.com/grandyang/p/4606710.html
基于合并两个有序链表的分治法确实很快啊!!!
【分治法 Divide and Conquer Approach】简单来说就是不停的对半划分,比如k个链表先划分为合并两个k/2个链表的任务,再不停的往下划分,直到划分成只有一个或两个链表的任务,开始合并。举个例子来说比如合并6个链表,那么按照分治法,我们首先分别合并1和4,2和5,3和6。这样下一次只需合并3个链表,我们再合并1和3,最后和2合并就可以了。参见代码如下:
/**
* 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.size() == 0) return NULL;
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];
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head = new ListNode(-1);
ListNode *cur = head;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return head->next;
}
};
Solution3:最小堆
基于C++ STL中的优先队列priority_queue可以实现最小堆
参考网址:http://www.cnblogs.com/grandyang/p/4606710.html
关于priority_queue的用法链接:https://www.cnblogs.com/calmwithdream/p/5281425.html
利用了最小堆这种数据结构,我们首先把k个链表的首元素都加入最小堆中,它们会自动排好序。然后我们每次取出最小的那个元素加入我们最终结果的链表中,然后把取出元素的下一个元素再加入堆中,下次仍从堆中取出最小的元素做相同的操作,以此类推,直到堆中没有元素了,此时k个链表也合并为了一个链表,返回首节点即可,代码如下:
【注意】:当比较函数是小于号时,优先队列是从大到小;当比较函数是大于号时,优先队列从小到大
struct cmp {//学习定义priority_queue的比较函数
bool operator () (ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
for (int i = 0; i < lists.size(); ++i) {
if (lists[i]) q.push(lists[i]);
}
ListNode *head = new ListNode(-1), *cur = head, *tmp = NULL;
while (!q.empty()) {
tmp = q.top();
q.pop();
cur->next = tmp;
cur = cur->next;
if (tmp->next) q.push(tmp->next);
}
return head->next;
}
};