题目
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
if(l1 == null)
return l2;
if(l2 == null)
return l1;
if(l1.val <= l2.val)
{
l1.next = MergeTwoLists(l1.next,l2) ;
return l1;
}
else
{
l2.next = MergeTwoLists(l1,l2.next) ;
return l2;
}
}
public ListNode MergeKLists(ListNode[] lists)
{
int n = lists.Length;
if(n == 0)
return null;
if(n == 1)
return lists[0];
if(n == 2)
return MergeTwoLists(lists[0], lists[1]);
int mid = n / 2;
ListNode[] l1 = new ListNode[mid];
ListNode[] l2 = new ListNode[n-mid];
for(int i = 0; i < mid; i++)
l1[i] = lists[i];
for(int i = mid, j = 0; i < n; i++, j++)
l2[j] = lists[i];
return MergeTwoLists(MergeKLists(l1),MergeKLists(l2));
}
}
实验结果
执行结果:通过
执行用时 :160 ms, 在所有 C# 提交中击败了98.13%的用户
内存消耗 :29.1 MB, 在所有 C# 提交中击败了6.38%的用户