[LeetCode]23. 合併K個排序鏈表(優先隊列;分治待作)

題目

合併 k 個排序鏈表,返回合併後的排序鏈表。請分析和描述算法的複雜度。算法

示例:網絡

輸入:
[
  1->4->5,
  1->3->4,
  2->6]
輸出: 1->1->2->3->4->4->5->6ide

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。code

題解

方法一 優先隊列

  • 分別取每一個鏈表的頭節點比較,將最小的做爲新鏈表的第一個節點。若這個節點後面還有節點,則將一個節點放入比較的集合。
  • 比較的集合使用優先隊列維護(堆實現)。

方法二 分治

todo排序

代碼

/**
 * 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 == null || lists.length == 0) {
            return null;
        }

        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {// 輔助結構:優先隊列
            @Override
            public int compare(ListNode o1, ListNode o2) {
                if (o1.val < o2.val)
                    return -1;
                if (o1.val > o2.val)
                    return 1;
                return 0;
            }
        });
        ListNode tempHead = new ListNode(-1);// temp.next爲結果鏈表
        ListNode pNode = tempHead;

        // 將全部鏈表頭加入優先隊列
        for (ListNode listNode : lists) {
            if (listNode != null) {
                queue.add(listNode);
            }
        }
        // 某節點加入結果鏈表後,若其後還有節點,則將該節點加入優先隊列等待處理
        while (!queue.isEmpty()) {
            pNode.next = queue.poll();
            pNode = pNode.next;
            if (pNode.next != null) {
                queue.add(pNode.next);
            }
        }
        return tempHead.next;
    }
}
相關文章
相關標籤/搜索