O(N Log K) time complexity, O(K) space complexity, Java solution


  • 0
    W
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        private static class Node extends ListNode implements Comparable<Node> {
            public int index;
            int val;
            
            public Node(int val, int index) {
                super(val);
                this.val = val;
                this.index = index;
            }
            
            public int compareTo(Node other) {
                if (this.val == other.val) {
                    return 0;
                }
                return this.val > other.val ? 1 : -1;
            }
            
            public String toString() {
                return String.valueOf(val);
            }
        }
        private void updateHeap(ListNode[] lists, PriorityQueue<Node> minHeap, int index) {
                if (lists[index] != null) {
                    minHeap.add(new Node(lists[index].val, index));
                    lists[index] = lists[index].next;
                } 
        }
        public ListNode mergeKLists(ListNode[] lists) {
            PriorityQueue<Node> minHeap = new PriorityQueue<>();
            for (int i = 0; i < lists.length; i++) {
                ListNode list = lists[i];
                if (list != null) {
                    minHeap.add(new Node(list.val, i));
                    lists[i] = list.next;
                }
            }
            Node head = null;
            Node tail = null;
            if (!minHeap.isEmpty()) {
                head = minHeap.poll();
                tail = head;
            } else {
                return null;
            }
        
            int index = tail.index;
            updateHeap(lists, minHeap, index);
            while (!minHeap.isEmpty()) {
                Node newTail = minHeap.poll();
                tail.next = newTail;
                tail = newTail;
                index = tail.index;
                updateHeap(lists, minHeap, index);
            }
            return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.