23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
最简单的思路是利用之前Merge 2 sorted Lists, 逐个相加,但是这种的时间复杂度会更高。
public ListNode MergeKLists(ListNode[] lists) { ListNode sentinel = null; for(int i = 0;i<lists.Count();i++) { sentinel = MergeTwoLists(sentinel,lists[i]); } return sentinel; } public ListNode MergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; var w1 = l1; var w2 = l2; var sentinel = new ListNode(-1); var dummy = sentinel; while(l1 != null && l2 != null) { if(l1.val >= l2.val) { sentinel.next = new ListNode(l2.val); sentinel = sentinel.next; l2 = l2.next; } else { sentinel.next = new ListNode(l1.val); sentinel = sentinel.next; l1 = l1.next; } } if(l1 == null) sentinel.next = l2; else sentinel.next = l1; return dummy.next; }
下面用跟merge sort一样的思路,merge 为k/2的linked list array, 然后merge
public ListNode MergeKLists(ListNode[] lists) { var size = lists.Count(); if(size==0) return null; if(size==1) return lists[0]; while(size>1) { int k = (size+1)/2; for(int i =0;i<size/2;i++) { lists[i] = MergeTwoLists(lists[i], lists[i+k]); } size = k; } return lists[0]; } public ListNode MergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; var w1 = l1; var w2 = l2; var sentinel = new ListNode(-1); var dummy = sentinel; while(l1 != null && l2 != null) { if(l1.val >= l2.val) { sentinel.next = new ListNode(l2.val); sentinel = sentinel.next; l2 = l2.next; } else { sentinel.next = new ListNode(l1.val); sentinel = sentinel.next; l1 = l1.next; } } if(l1 == null) sentinel.next = l2; else sentinel.next = l1; return dummy.next; }