23. Merge k Sorted Lists

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

一刷
题解:
使用min heap构建的priority queue, 遍历输入数组,将非空表头节点加入min PQ,每次从PQ中poll()出最小值作为当前结果,之后加入取出节点的下一个非空节点。 当min PQ为空时结束。

Time Complexity - O(nlogn), Space Complexity - O(m), m为输入数组的length

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        PriorityQueue minPQ = new PriorityQueue(lists.length, new Comparator(){
            public int compare(ListNode a, ListNode b){
                return a.val - b.val;
            }
        });
        
        
        for(ListNode node:lists){
            if(node!=null){
                minPQ.offer(node);
            }
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        
        while(minPQ.size() > 0){
            ListNode tmp = minPQ.poll();
            node.next = tmp;
            if(tmp.next!=null) minPQ.offer(tmp.next);
            node = node.next;
        }
        
        return dummy.next;
    }

二刷:
思路相同,用PriorityQueue存储node

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        PriorityQueue queue = new PriorityQueue(lists.length, new Comparator(){
           public int compare(ListNode a, ListNode b){
               return a.val - b.val;
           }
        });
        
        for(ListNode node : lists){
            if(node!=null) queue.offer(node);
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        
        while(queue.size()>0){
            ListNode list = queue.poll();
            cur.next = list;
            list = list.next;
            cur = cur.next;
            if(list!=null) queue.offer(list);
        }
        
        return dummy.next;
    }
}

}

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