23.Merge k Sorted Lists

Hard
这个题 我一开始没想到用Priority Queue, 想的是每次遍历整个lists找最小的来接上。其实思路本质上是一样的,但太麻烦而且说明你对priority queue不熟。吓得我赶紧做implement priority queue.

/**
 * 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.length == 0 || lists == null){
            return null;
        }
        PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, sortByValue);
        for (ListNode node : lists){
                if (node != null){
                    pq.offer(node);
                }
        }
        ListNode dummy = new ListNode(-1);
        ListNode curt = dummy;
        while (!pq.isEmpty()){
            ListNode smallest = pq.poll();
            if (smallest.next != null){
                pq.offer(smallest.next);
            }
            curt.next = smallest;
            smallest.next = null;
            curt = curt.next;
        }
        return dummy.next;              
    }
    
    public Comparator<ListNode> sortByValue = new Comparator<ListNode>(){
        public int compare(ListNode l1, ListNode l2){
            return l1.val - l2.val;
        }
    };
    
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/0cd7ac60e0be
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞