[LeetCode] 23 - Merge k Sorted Lists
2015-08-29 16:47
561 查看
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) {
if (lists.empty()) {
return nullptr;
}
auto comp_func = [](ListNode* a, ListNode* b){ return (a->val >= b->val);};
vector<ListNode*> heap;
for (auto node : lists) {
if (node) {
heap.emplace_back(node);
}
}
ListNode head_node(-1);
ListNode *head = &head_node;
make_heap(heap.begin(), heap.end(), comp_func);
while (!heap.empty()) {
pop_heap(heap.begin(), heap.end(), comp_func);
auto &node = heap.back();
heap.pop_back();
head->next = node;
head = node;
if (node->next) {
heap.emplace_back(node->next);
push_heap(heap.begin(), heap.end(), comp_func);
}
}
return head_node.next;
}
};
/**
* 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 nullptr;
}
auto comp_func = [](ListNode* a, ListNode* b){ return (a->val >= b->val);};
vector<ListNode*> heap;
for (auto node : lists) {
if (node) {
heap.emplace_back(node);
}
}
ListNode head_node(-1);
ListNode *head = &head_node;
make_heap(heap.begin(), heap.end(), comp_func);
while (!heap.empty()) {
pop_heap(heap.begin(), heap.end(), comp_func);
auto &node = heap.back();
heap.pop_back();
head->next = node;
head = node;
if (node->next) {
heap.emplace_back(node->next);
push_heap(heap.begin(), heap.end(), comp_func);
}
}
return head_node.next;
}
};
相关文章推荐
- 我关注的一周技术动态 2015.08.30
- localhost与127.0.0.1的区别
- 使用Jedis源码生成Jedis.jar
- C++中map、hash_map、unordered_map、unordered_set通俗辨析
- 在Mac上制作树莓派SD镜像
- Intellij IDEA 修改字体
- Android 如何在Eclipse中查看Android API源码以及support包源码
- linux内核之字符驱动
- 【LeetCode】67. Add Binary
- ios的属性和成员变量在.h文件和.m文件的不同
- Python爬虫框架Scrapy教程(1)—入门
- 1063 -- 发奖学金咯^_^
- Genealogical tree(拓扑排序)
- UDP客户端实现在不同端口上发送和接收数据
- 解决IOS 系统浏览器 html scroll-x 不起作用的办法
- MySQL 性能优化详解
- super-diamond配置管理系统
- 编写队列 初始化时发现 rear, front指向末尾的好处 <Java>
- 1062 -- 最左边一位数
- 1061 -- 最小公倍数