23. Merge k Sorted Lists

  1. 原题: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. (合并 k 个已排序的linked list 并作为一个 list 返回,分析和描述它的复杂度。)
  2. 解法: 由于之前做过合并2个已排序 list,所以这里自然想到用递归
  3. AC解:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return recursion(lists, 0, lists.length - 1);
    }

    public ListNode recursion(ListNode[] lists, int start, int end) {
        if(start == end) return lists[start];
        if(start < end) {
            int center = (start + end) / 2;
            ListNode l1 = recursion(lists, start, center);
            ListNode l2 = recursion(lists, center + 1, end);
            return mergeTwoLists(l1, l2);
        }else {
            return null;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode tail= dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                tail.next = l1;
                l1 = l1.next;
            } else {
                tail.next = l2;
                l2 = l2.next;
            }
            tail = tail.next;
        }
        tail.next = l1 == null ? l2 : l1;
        return dummy.next;
    }
}