问题描述
* leetcode 23, Merge k Sorted Lists
解题思路
-
合并2个有序链表的进阶版,很容易想到,利用分治进行处理。
把个数大于2的集合 两两划分处理,最后再做最后一步的处理。
1 public class Solution {
2 public ListNode mergeKLists(ListNode[] lists) {
3 if (lists.length==0 || lists==null) { return null; }
4 return merge(lists, 0, lists.length-1);
5 }
6 public static ListNode merge(ListNode[] lists, int left, int right) {
7 if (left == right) { return lists[left]; }
8 int mid = left + (right-left)/2;
9 ListNode l1 = merge(lists, left, mid);
10 ListNode l2 = merge(lists, mid+1, right);
11 return merger2Lists(l1, l2);
12 }
13 public static ListNode merger2Lists(ListNode l1, ListNode l2) {
14 // 递归写法
15 if (l1==null) { return l2; }
16 if (l2==null) { return l1; }
17 ListNode head = null;
18 if (l1.val < l2.val) {
19 head = l1;
20 head.next = merger2Lists(l1.next, l2);
21 } else {
22 head = l2;
23 head.next = merger2Lists(l1, l2.next);
24 }
25 return head;
26 }
27 }
28