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

Method 1:
class Solution {
    private ListNode findMin(ListNode[] lists) {
        int size = lists.length;
        int minVal = Integer.MAX_VALUE;
        int minInd = -1;
        ListNode minNode = null;
        for(int i = 0; i < size; i++) {
            if(lists[i] == null) continue;
            if(lists[i].val < minVal) {
                minVal = lists[i].val;
                minInd = i;
                minNode = lists[i];
            }
        }
        if(minInd != -1) lists[minInd] = lists[minInd].next; //把minNode下一个加进lists
        return minNode;
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;

        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while(head != null) {
            head.next = findMin(lists);
            head = head.next;
        }
        return dummy.next;
    }
}



Method 2:
class Solution {
    private Comparator<ListNode> listComparator = new Comparator<ListNode> () {
        public int compare(ListNode first, ListNode second) {
            return first.val - second.val;
        }
    };

    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;

        Queue<ListNode> heap = new PriorityQueue<ListNode> (lists.length, listComparator);

        for(int i = 0; i < lists.length; i++) {
            if(lists[i] != null) heap.add(lists[i]);
        }

        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while(!heap.isEmpty()) {
            ListNode choose = heap.poll();
            head.next = choose;
            head = head.next;
            if(choose.next != null) heap.add(choose.next); //把choose的下一个加进heap
        }
        return dummy.next;
    }
}


和method2一样,只是comparator的写法变下
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;

        Queue<ListNode> heap = new PriorityQueue<> (lists.length, new Comparator<ListNode>() {
            public int compare(ListNode node1, ListNode node2) {
                return node1.val - node2.val;
            }
        });

        for(int i = 0; i < lists.length; i++) {
            if(lists[i] != null) heap.add(lists[i]);
        }

        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while(!heap.isEmpty()) {
            ListNode choose = heap.poll();
            head.next = choose;
            head = head.next;
            if(choose.next != null) heap.add(choose.next); //把choose的下一个加进heap
        }
        return dummy.next;
    }
}

results matching ""

    No results matching ""