leetcode.23. Merge k Sorted Lists
2016-05-20 18:01
225 查看
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) {} * }; */ struct CompareListNode{ bool operator()(const ListNode*p, const ListNode* q)const{ return p->val > q->val; } }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode head(-1); vector<ListNode*> vec_helper; //除去空链表 for (int i=0; i<lists.size(); i++) { if (lists[i]!=NULL) vec_helper.push_back(lists[i]); } //建小堆 std::make_heap(vec_helper.begin(), vec_helper.end(), CompareListNode()); ListNode* pTail = &head; while (vec_helper.size() > 0) { //取最小的元素对应的节点 ListNode *pNode = vec_helper.front(); pTail->next= pNode; pTail = pTail->next; std::pop_heap(vec_helper.begin(), vec_helper.end(), CompareListNode()); vec_helper.pop_back(); //将该节点之后一个节点加堆中 if (pNode->next) { vec_helper.push_back(pNode->next); std::push_heap(vec_helper.begin(), vec_helper.end(), CompareListNode()); } } pTail->next = NULL; return head.next; } };
相关文章推荐
- Android 实现在Activity中操作刷新另外一个Activity数据列表
- mysql的基本知识
- DOS命令详解
- cocoapods
- cocos2d-x SpriteFrameCache
- Mysql 授权用户进行远程连接
- cocos2d-x动画
- 慢查询slowlog记录日志问题
- 如何在Eclipse中自定义类似syso的快捷代码模板
- C# 导入EXCEL 报错:外部表不是预期的格式
- Redis集群使用总结(一)
- 深入了解生成随机数的函数rand()
- Android属性动画
- MQ通道配置示例(2):Server/Requester
- cocos2dx 3.x事件监听
- 机器码下的多态类型推导-Polymorphic type inference for machine code
- 谁在潇洒的走
- Spring整合JMS
- PHP新手之学习类与对象
- Windows下Git的安装及配置