LeetCode题解:Merge k Sorted Lists
来源:互联网 发布:sql sever 导入 excel 编辑:程序博客网 时间:2024/06/05 03:08
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity
思路:
标准的merge sort使用min(x,y),这里需要的是min(x1, x2, ... xk),可以用堆实现。
/** * 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) { using node_pair = pair<ListNode*, size_t>; // Note: By default, C++ will create a max-heap, but we need a min-heap auto comparison=[](const node_pair& n1, const node_pair& n2) -> bool { return n1.first->val > n2.first->val; }; // starting point of the list ListNode* new_start = new ListNode(0); ListNode* new_last = new_start; // Heap, storing the first node of each list vector<node_pair> v_nodes; v_nodes.reserve(lists.size()); // initalize the heap size_t index=0; for(auto& t : lists) { if (t!=nullptr) { v_nodes.push_back(node_pair(t, index)); t=t->next; } index++; } make_heap(begin(v_nodes), end(v_nodes),comparison); // Heap injector auto inject_heap=[&v_nodes,&lists,&comparison](const size_t list_id) -> void { if (lists[list_id]==nullptr) return; else { auto save = lists[list_id]; lists[list_id]=save->next; v_nodes.push_back(node_pair(save, list_id)); push_heap(begin(v_nodes), end(v_nodes), comparison); } }; // Loop until the heap is empty while(!v_nodes.empty()) { pop_heap(begin(v_nodes), end(v_nodes), comparison); auto t = v_nodes.back(); v_nodes.pop_back(); new_last->next = t.first; new_last = new_last->next; inject_heap(t.second); } // drop the head new_last=new_start; new_start=new_start->next; delete new_last; return new_start; }};
- LeetCode题解:Merge k Sorted Lists
- Leetcode题解-23. Merge k Sorted Lists
- leetcode题解-23. Merge k Sorted Lists
- LeetCode 题解(79): Merge k Sorted Lists
- LeetCode题解——Merge k Sorted Lists
- leetcode题解c++ | 23. Merge k Sorted Lists
- LeetCode: Merge k Sorted Lists
- LeetCode Merge k Sorted Lists
- LeetCode: Merge k Sorted Lists
- [Leetcode] Merge k Sorted Lists
- [Leetcode] Merge k Sorted Lists
- [Leetcode] Merge K sorted lists
- [LeetCode]Merge k Sorted Lists
- [LeetCode] Merge k Sorted Lists
- LeetCode-Merge k Sorted Lists
- LeetCode: Merge k Sorted Lists
- LeetCode - Merge k Sorted Lists
- LeetCode | Merge k Sorted Lists
- 【每天学点算法题10.18】找出数组中的第K大的数
- 计算机程序的构造与解释作业:练习1.1到1.5
- 大学生活
- IOS单例模式及单例模式的优缺点
- 1-12 实验10 网络管理实验2 已知网络地址查询MAC地址
- LeetCode题解:Merge k Sorted Lists
- C++中动态内存分配引发问题的解决方案
- 【进村记】电子产品实体店的几大骗术分析
- starvation at com.timesten.jdbc.JdbcOdbcDirect.paramData(long, byte[])
- POJ 3292 Semi-prime H-numbers(打表)
- Bjarne:如何对付内存泄漏?
- tomcat 中文乱码修正
- 菜鸟也能搞定C++内存泄漏
- java IO流 读取文件 && 文件复制