23. Merge k Sorted Lists

23. Merge k Sorted Lists

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

My Solution:

  • Use divide and conquer to merge sort all nodes in each list

  • 参考 #21

  • Time : O(Nlogk) where k is the number of linked lists.

    • We can merge two sorted linked list in O(n) time where n is the total number of nodes in two lists.

    • Sum up the merge process and we can get: O(Nlogk)

  • Space : O(1)

/**
 * 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 helper(lists, 0, lists.length - 1);
    }
    
    public ListNode helper(ListNode[] lists, int l, int r) {
        if (l == r) {
            return lists[l];
        } else if (l < r) {
            int m = l + (r - l) / 2;
            return merge(helper(lists, l, m), helper(lists, m + 1, r));
        } else {
            return null;
        }
    }
    
    public ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        
        ListNode dummy = new ListNode(0);
        ListNode node = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        
        if (l1 != null) node.next = l1;
        else node.next = l2;
        
        return dummy.next;
    }
}

Last updated