23. Merge k Sorted Lists

Description

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

Solution

Divide & Conquer, time O(n * log n), 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) {
            return null;
        }
        
        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;
        return merge(mergeKLists(lists, start, mid)
                     , mergeKLists(lists, mid + 1, end));
    }
    
    public ListNode merge(ListNode p, ListNode q) {
        if (p == null) {
            return q;
        }
        if (q == null) {
            return p;
        }
        
        if (p.val <= q.val) {
            p.next = merge(p.next, q);
            return p;
        } else {
            q.next = merge(p, q.next);
            return q;
        }
    }
}

MinHeap, time O(k * log k), space O(k)

/**
 * 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) {
            return null;
        }
        
        PriorityQueue queue
            = new PriorityQueue((a, b) -> a.val - b.val);
        for (ListNode list : lists) {
            if (list == null) continue;
            queue.offer(list);
        }
        
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        
        while (!queue.isEmpty()) {
            ListNode p = queue.poll();
            tail.next = p;
            tail = p;
            if (p.next == null) continue;
            queue.offer(p.next);
        }
        
        return dummy.next;
    }
}

你可能感兴趣的:(23. Merge k Sorted Lists)