1. 程式人生 > 實用技巧 >合併K個排序連結串列

合併K個排序連結串列

思路:用容量為K的最小堆優先佇列,把連結串列的頭結點都放進去,然後出隊當前優先佇列中最小的,掛上連結串列,,然後讓出隊的那個節點的下一個入隊,再出隊當前優先佇列中最小的,直到優先佇列為空。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        Queue<ListNode> pq = new PriorityQueue<>((x,y)->x.val-y.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;
    }
}

程式碼源於:https://leetcode-cn.com/problems/merge-k-sorted-lists/comments/