Leetcode -- Merge k Sorted Lists
2015-10-23 20:39
239 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
本题使用优先队列,自定义优先级。
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: struct cmp { bool operator ()(pair<int,int> &a,pair<int,int> &b) { return a.first>b.first; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode *h = new ListNode(-1),*p = h; priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> que; int n = lists.size(); for(int i=0;i<n;++i) if(lists[i]) { que.push(make_pair(lists[i]->val,i)); } while(!que.empty()) { auto tmp = que.top(); que.pop(); int val = tmp.first,idx = tmp.second; p->next = lists[idx]; lists[idx] = lists[idx]->next; if(lists[idx]) { que.push(make_pair(lists[idx]->val,idx)); } p = p->next; } p = h->next; delete h; return p; } };
相关文章推荐
- 我前妻的故事(一个初中肄业生的奋斗)
- JAVA除去制定字符的方法
- POJ 2192 【DP】
- hdoj--2767--Proving Equivalences (scc+缩点)
- HDOJ 2112 HDU Today(最短路--dijkstra)
- 解决方法参数为arg0,arg1的问题
- 序列检测器改编
- hdoj--2767--Proving Equivalences (scc+缩点)
- Mahout分类算法学习之实现Naive Bayes分类示例
- hdu2509Be the Winner(尼姆博弈)
- HomeKit用户界面指南(中文版)
- 编程思想
- 运维
- 初识Spark
- ecmall利用Tree.lib实现三级分类目录的输出
- NiftyDialogEffects-master 使用详解
- CommonJs AMD CMD 模块加载
- 跟着猫哥学Golang[1] - Hello World!
- jqgrid动态显示/隐藏某一列
- Linux串口工具minicom配置