【详细整理】23 合并K个升序链表

252 阅读1分钟

题目

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

思路一、归并+双链表合并

将每一个链表看做一个元素,利用归并的分治思想进行处理。

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0){return null;}
        return merge(0,lists,lists.length-1);
    }
    public ListNode merge(int left,ListNode[] lists,int right){
        // if(left == right){return null;}
        if(left == right){return lists[left];}
        int mid = left + (right-left) >>1;
        ListNode l = merge(left,lists,mid);
        ListNode r = merge(mid+1,lists,right);
        return paixu(l,r);
    }
    public ListNode paixu(ListNode l,ListNode r){
        if(l == null){return r;}
        if(r == null){return l;}
        if(l.val <= r.val){
            l.next = paixu(l.next,r);
            return l;
        }else{
            r.next = paixu(l,r.next);
            return r;
        }
        

    }


}

思路2、优先队列排序

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {

        if (lists.length == 0) {
            return null;
        }

        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });

        for (ListNode list : lists) {
            if (list == null) {
                continue;
            }
            pq.add(list);
        }

        while (!pq.isEmpty()) {
            ListNode nextNode = pq.poll();
            curr.next = nextNode;
            curr = curr.next;
            if (nextNode.next != null) {
                pq.add(nextNode.next);
            }
        }
        return dummyHead.next;
    }
}