23 Merge k Sorted Lists

1. Question

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

2. Implementation

(1) Divide and Conquer

/**
 * 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 mergeKLists(lists, 0, lists.length - 1);
    }

    public ListNode mergeKLists(ListNode[] lists, int start, int end) {
        if (start > end) {
            return null;
        }

        if (start == end) {
            return lists[start];
        }

        int mid = start + (end - start) / 2;
        ListNode left = mergeKLists(lists, start, mid);
        ListNode right = mergeKLists(lists, mid + 1, end);
        return mergeTwoLists(left, right);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode curNode = dummy;
        ListNode p1 = l1, p2 = l2;

        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                curNode.next = p1;
                p1 = p1.next;
            }
            else {
                curNode.next = p2;
                p2 = p2.next;
            }
            curNode = curNode.next;
        }

        if (p1 != null) {
            curNode.next = p1;
        }
        else {
            curNode.next = p2;
        }
        return dummy.next;
    }
}

(2) Heap

/**
 * 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;
        }

        PriorityQueue<ListNode> minHeap = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }
        });

        for (ListNode head : lists) {
            if (head != null) {
                minHeap.add(head);
            }
        }

        ListNode dummy = new ListNode(0);
        ListNode curNode = dummy;

        while (!minHeap.isEmpty()) {
            curNode.next = minHeap.remove();
            curNode = curNode.next;

            if (curNode.next != null) {
                minHeap.add(curNode.next);
            }
        }
        return dummy.next;
    }
}

3. Time & Space Complexity

Divide and Conquer: 时间复杂度O(nlogk), k是lists的个数, n是merge两个list时,两个list的node总个数,空间复杂度O(1)

Heap: 时间复杂度O(nlogk), k是lists的个数, n是所有list的node的总数,空间复杂度O(k)

Last updated