leetcode 023 —— Merge k sorted linked lists
2015-07-13 14:24
363 查看
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) {
vector<ListNode*>::iterator it = lists.begin();
while(it != lists.end()) {
if(*it == NULL) lists.erase(it);
else ++it;
}
if(lists.size() < 1) return NULL;
ListNode *head = NULL, *cur = NULL;
make_heap(lists.begin(), lists.end(), comp());
while(lists.size() > 0) {
if(head == NULL) head = cur = lists[0];
else cur = cur->next = lists[0];
pop_heap(lists.begin(), lists.end(), comp());
int last = lists.size() - 1;
if(lists[last]->next != NULL) {
lists[last] = lists[last]->next;
push_heap(lists.begin(), lists.end(), comp());
}
else lists.pop_back();
}
return head;
}
class comp {
public:
bool operator() (const ListNode* l, const ListNode* r) const {
return (l->val > r->val);
}
};
};
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) {
vector<ListNode*>::iterator it = lists.begin();
while(it != lists.end()) {
if(*it == NULL) lists.erase(it);
else ++it;
}
if(lists.size() < 1) return NULL;
ListNode *head = NULL, *cur = NULL;
make_heap(lists.begin(), lists.end(), comp());
while(lists.size() > 0) {
if(head == NULL) head = cur = lists[0];
else cur = cur->next = lists[0];
pop_heap(lists.begin(), lists.end(), comp());
int last = lists.size() - 1;
if(lists[last]->next != NULL) {
lists[last] = lists[last]->next;
push_heap(lists.begin(), lists.end(), comp());
}
else lists.pop_back();
}
return head;
}
class comp {
public:
bool operator() (const ListNode* l, const ListNode* r) const {
return (l->val > r->val);
}
};
};
相关文章推荐
- swift数组
- Chrome禁用NPAPI插件(包括 Silverlight、Java 和 Unity)
- 界面布局优化
- [LeetCode]Implement strStr() 字符串匹配
- 使用Spring Boot快速构建应用
- jQuery 遍历 - slice() 方法
- 后Hadoop时代的大数据架构(转)
- Codeforces 450 B. Jzzhu and Sequences
- SQL2008--行号的得到
- Android开发自定义popupwindow
- 上课笔记--财务管理
- Qt跨平台的一个例程
- Please allow Subclipse team to receive anonymous usage statistics for this Eclipse intance(info)
- 谈谈商城网站建设要优化的重点,包括图片优化!
- iOS判断是否有权限访问相机,相册,定位
- Visual Studio 调试小技巧(2) - 从查看窗口得到更多信息
- bzoj1079 dp
- 两张表关联,根据一张表更新另一张表
- 嵌入式Linux串口应用编程
- 2015年程序员生存报告,苦还是不苦