小顶堆算法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0){
            return null;
        }
        Queue<ListNode> queue = new PriorityQueue<>((ListNode a, ListNode b) -> (a.val - b.val));

        for(ListNode list : lists){
            while(list != null){
                queue.add(list);
                list = list.next;
            }
        }
        ListNode node = new ListNode(-1);
        ListNode h = node;
        while(!queue.isEmpty()){
            ListNode poll = queue.poll();
            node.next = poll;
            node = node.next;
            node.next = null;
        }
        return h.next;
    }
}

使用PriorityQueue实现类,重写ComparaTor的compare方法,实现队列内添加自动排序

 

posted @ 2021-09-09 10:15  K峰  Views(72)  Comments(0)    收藏  举报