【LeetCode】Merge k Sorted Lists

利用优先队列进行合并,要学会使用JDK中的优先队列PriorityQueue,PriorityQueue一般都是基于HEAP实现的。

基于HEAP实现的PriorityQueue复杂度分析:

add(E e): O(lg n)

peek(); 获取优先队列的头

poll()://获取优先队列的头,同时在该优先队列中删除该节点   O(lg n) (注意,取出元素只需要O(1), 但是维护HEAP结构需要 O(lg n))

remove(E e): O(n)


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {

    public ListNode mergeKLists(List<ListNode> lists) {
        if(lists == null || lists.size() == 0)return null;
        else if(lists.size() == 1) return lists.get(0);
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        PriorityQueue <ListNode> priorityQueue = new PriorityQueue<ListNode> (11 ,new Comparator<ListNode>(){
            public int compare(ListNode o1, ListNode o2){
                return o1.val - o2.val;
            }
        });
        for(int i=0; i<lists.size(); i++){
            if(lists.get(i) != null){
                priorityQueue.add(lists.get(i));
            }
        }
        while(priorityQueue.size() > 0){
            ListNode curNode = priorityQueue.poll();
            p.next = curNode;
            p = p.next;
            if(curNode.next != null) priorityQueue.add(curNode.next);
        }
        return dummy.next;
    }
}





你可能感兴趣的:(【LeetCode】Merge k Sorted Lists)