23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

1
2
3
4
5
6
7
Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        return sortByPartition(lists, 0, lists.length-1);
    }

    private ListNode sortByPartition(ListNode[] lists, int start, int end){
        /*
        * 递归先确定结束条件
        * */
        if (start == end){
            return lists[start];
        }
        /*
        * 经典的分治理念,切半,递归递归,合并
        * */
        int mid = start+(end-start)/2;
        ListNode left = sortByPartition(lists, start, mid);
        ListNode right = sortByPartition(lists, mid+1, end);
        return merge(left,right);
    }

    private ListNode merge(ListNode left, ListNode right){
        /*
        * 同样是递归,先要确定结束条件
        * */
        if (left == null || right == null){
            return left == null ? right : left;
        }
        /*
        * 链表合并总是要有连接的过程的,这边需要额外注意
        * */
        if (left.val<right.val){
            left.next = merge(left.next,right);
            return left;
        }
        else {
            right.next = merge(left,right.next);
            return right;
        }
    }
}

非常经典非常好的题-多链表按序合并 - 可以使用优先级队列(但是这样使用了内建函数) - 最后参考的方法是分治,其有着有一定的规律,比如先中分,俩边递归,然后合并

  • 链表合并的递归函数还是蛮经典的,之后要会默写