合併 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; } }