合并 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 MergeKLists(ListNode[] lists) { ListNode res = new ListNode(0); ListNode p = res; List<ListNode> index = new List<ListNode>(); for(int i=0; i<lists.Length; i++) { ListNode node = new ListNode(0); node.next = lists[i]; index.Add(node); } while(index.Count != 0) { List<int> mins = new List<int>(); int min = int.MaxValue; for(int i=index.Count-1; i>=0; i--) { if(index[i].next != null) { if (index[i].next.val < min) { min = index[i].next.val; mins.Clear(); mins.Add(i); } else if (index[i].next.val == min) { mins.Add(i); } } } for(int i=0; i<mins.Count; i++) { ListNode node = new ListNode(index[mins[i]].next.val); p.next = node; p = node; index[mins[i]] = index[mins[i]].next; } for(int i = index.Count - 1; i >= 0; i--) { if(index[i].next == null) { index.Remove(index[i]); } } } return res.next; } }