LeetCode 23. Merge k Sorted Lists
来源:互联网 发布:软件研究所 导师 编辑:程序博客网 时间:2024/06/07 21:01
一、题目描述
Merge k sorted linked lists and return it as one sorted list. Analyze
and describe its complexity.
题意:给定k个有序链表,将这k个链表合并成一个链表,使其元素按照升序排列
二、解题思路
利用优先队列(队列为顶端小)保存k个指向给定链表的指针,每次在优先队列中取出top所存指针(即为k个结点中val值最小的),并创建一个val值等于该top结点val值的新结点,加入到输出链表尾部。取出top指针后,调用pop()函数将其删除,并将其指向的下一个结点的指针存进优先队列并重复上述过程,直到优先队列为空,则过程结束
三、C++代码
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};struct cmp { bool operator() (const ListNode* one, const ListNode* two) { return one->val > two->val; }};class Solution {public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode* head = new ListNode(0); ListNode* temp = head; priority_queue<ListNode*,vector<ListNode*>,cmp> pointer; for (int i = 0; i < lists.size(); i++) { if (lists[i] != NULL) pointer.push(lists[i]); } while (!pointer.empty()) { temp->next = new ListNode(pointer.top()->val); ListNode* p = pointer.top(); temp = temp->next;//temp指向刚被pop出来的最小值 pointer.pop(); if (p->next != NULL) { pointer.push(p->next); } } return head->next; }};
阅读全文
0 0
- leetcode 23. LeetCode Merge k Sorted Lists
- [LeetCode]23.Merge k Sorted Lists
- LeetCode --- 23. Merge k Sorted Lists
- LeetCode 23.Merge k Sorted Lists
- [Leetcode] 23. Merge k Sorted Lists
- 【LeetCode】23.Merge k Sorted Lists
- [leetcode] 23.Merge k Sorted Lists
- Leetcode-23.Merge k Sorted Lists
- [Leetcode]23. Merge k Sorted Lists @python
- leetcode 23. Merge k Sorted Lists
- leetcode 23. Merge k Sorted Lists
- leetcode 23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists
- [leetcode] 23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists
- LeetCode-23.Merge k Sorted Lists
- Leetcode 23. Merge k Sorted Lists
- 10/30 fb面经
- python的中文数组输出乱码问题
- linux中的定时及延时任务
- 老查的ARM学习笔记:chapter-2(linux总线设备驱动详解)
- 第四讲 类加载器的委托
- LeetCode 23. Merge k Sorted Lists
- How to: Shellcode to reverse bind a shell with netcat
- [51nod1920]空间统计学
- 第八章作业
- Python正则表达式(二)代码
- 记阿里UC跟cvte社招面试-----都挂了~
- 《刻意练习》读书笔记
- opencv学习——保存至github
- Ubuntu下搭建python开发环境