Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null
.
SOLUTION:
几个list一起merge的话,应该能算是,merge 2 sorted list -->follow up-->merge 2 unsorted list -->follow up--> merge k sorted list,一个follow up的过程。这个一样用递归去做,简单明了。做一个递归函数helper();这是因为传入参数跟原来的不一样,不然是可以直接递归的。然后list当然也要二分一下,然后需要用的就是list的size,然后,left = helper(lists, start, mid); right = helper(lists, mid + 1, end); 最后merge(left, right)就OK了。
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ public ListNode mergeKLists(List<ListNode> lists) { if (lists == null || lists.size() == 0){ return null; } int size = lists.size(); return helper(lists, 0, size - 1); } private ListNode helper(List<ListNode> lists, int start, int end){ if (start < end){ int mid = start + (end - start) / 2; return merge(helper(lists, start, mid), helper(lists, mid + 1, end)); } return lists.get(start); } private ListNode merge(ListNode l1, ListNode l2){ if (l1 == null){ return l2; } if (l2 == null){ return l1; } ListNode dummy = new ListNode(0); ListNode head = dummy; while (l1 != null && l2 != null){ if (l1.val < l2.val){ head.next = l1; l1 = l1.next; head = head.next; } else { head.next = l2; l2 = l2.next; head = head.next; } } if (l1 != null){ head.next = l1; } if (l2 != null){ head.next = l2; } return dummy.next; } }
[LintCode] Merge k Sorted Lists
原文:http://www.cnblogs.com/tritritri/p/4971163.html