- Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
题目解析:21题是合并二个链表,此题是21题的升级版,合并多个链表,借助于21题的函数,将第一个链表赋给新建链表,然后将此链表与后面的链表进行比较合并,方法比较暴力,筒子们也可以去看看博客其他大神的博客,优化算法。
代码:
/**
* 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) {
ListNode * merge = new ListNode(0);//新建链表
ListNode * head = merge;
if(lists.size() == 0)
{
return NULL;
}
head = lists[0];//第一个链表赋给新建链表
if(lists.size() > 1)
{
for(int i= 1;i<lists.size();i++)
{
head = mergeTwoLists(head,lists[i]);//合并二个链表,赋给新建链表
}
}
return head;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {//合并链表函数
ListNode * merge = new ListNode(0);
ListNode * cur = merge;
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
while(l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1 != NULL)
{
cur->next = l1;
}
if(l2 != NULL)
{
cur->next = l2;
}
return merge->next;
}
};
性能:
总结:方法属于暴力破解,性能不佳,可优化,其他方法都是借助于二个链表合并的函数,后面对怎么传入二个链表进行优化,大家可提供思路。