23. Merge k Sorted Lists
2016-07-13 11:51
351 查看
1.问题描述
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
2.解题思路
类似于2路归并法,将K路归并划为2路归并,直到最后得到一个链表,采用递归的方法
3.代码实现
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr)
return l2;
else if (l2 == nullptr)
return l1;
ListNode *head; //合并后的头节点
if (l1->val > l2->val)
{
head = l2;
l2 = l2->next;
}
else
{
head = l1;
l1 = l1->next;
}
ListNode *r = head;//r保存合并节点的尾节点
//逐一合并
while (l1&&l2)
{
if (l1->val <= l2->val)
{
r->next = l1;
l1 = l1->next;
}
else
{
r->next = l2;
l2 = l2->next;
}
r = r->next;
}
if (l1)
r->next = l1;
if (l2)
r->next = l2;
return head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty())
return nullptr;
if (lists.size() ==1)
return lists[0];
int len = lists.size() % 2 + lists.size() / 2;
vector<ListNode*> v;
vector<ListNode>::size_type i = 0, j = i + 1;
while (i < lists.size())
{
if (j != lists.size())
v.push_back(mergeTwoLists(lists[i], lists[j]));
else
v.push_back(mergeTwoLists(lists[i], nullptr));
i += 2;
j += 2;
}
return mergeKLists(v);
}
};
4.复杂度:
总共K个链表,合并K个链表需要logK次,每次时间复杂度为O(m+n),复杂度为O(logK*(m+n))
5.实现截图
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
2.解题思路
类似于2路归并法,将K路归并划为2路归并,直到最后得到一个链表,采用递归的方法
3.代码实现
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr)
return l2;
else if (l2 == nullptr)
return l1;
ListNode *head; //合并后的头节点
if (l1->val > l2->val)
{
head = l2;
l2 = l2->next;
}
else
{
head = l1;
l1 = l1->next;
}
ListNode *r = head;//r保存合并节点的尾节点
//逐一合并
while (l1&&l2)
{
if (l1->val <= l2->val)
{
r->next = l1;
l1 = l1->next;
}
else
{
r->next = l2;
l2 = l2->next;
}
r = r->next;
}
if (l1)
r->next = l1;
if (l2)
r->next = l2;
return head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty())
return nullptr;
if (lists.size() ==1)
return lists[0];
int len = lists.size() % 2 + lists.size() / 2;
vector<ListNode*> v;
vector<ListNode>::size_type i = 0, j = i + 1;
while (i < lists.size())
{
if (j != lists.size())
v.push_back(mergeTwoLists(lists[i], lists[j]));
else
v.push_back(mergeTwoLists(lists[i], nullptr));
i += 2;
j += 2;
}
return mergeKLists(v);
}
};
4.复杂度:
总共K个链表,合并K个链表需要logK次,每次时间复杂度为O(m+n),复杂度为O(logK*(m+n))
5.实现截图
相关文章推荐
- woj1208 Sherlock's Code
- SDUT_有序单链表归并
- 大数阶乘
- 记一次神奇的优化过程:Java反射 VS Apache BeanUtils VS Spring BeanUtils
- jquery鼠标移上div切换
- 文本挖掘的基本流程
- 一个男人关心的东西 决定了他的层次
- 配置jdk的几个方法
- JavaScript在IE6下超级链接window.location.href不跳转的bug 及 解决方案
- iOS数据存储
- 向hehe同学学习
- 面向对象(Object类方法重写)day11
- Android WebService 提交数据
- 7、在MyEclipse中自动生成接口
- as3 操作图片,获取,设置实际像素,扣除透明区域
- js数据类型
- iOS中保证线程安全的几种方式与性能对比
- web.xml 中的listener、 filter、servlet 加载顺序及其详解
- System.getProperty()参数大全
- System.Reflection.Emit学习