執行結果:
通過
顯示詳情
執行用時 :5 ms, 在所有 Java 提交中擊敗了62.48% 的用戶
內存消耗 :41.8 MB, 在所有 Java 提交中擊敗了55.30%的用戶
題目:
合併 k 個排序鏈表,返回合併後的排序鏈表。請分析和描述算法的複雜度。
示例:
輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
將所有鏈表的頭節點維護成一個優先隊列,哪個節點出隊了,就把它的下一個節點加入。
代碼:
/**
* 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;
}
PriorityQueue<ListNode> queue=new PriorityQueue<>(new Comparator<ListNode>(){
public int compare(ListNode a,ListNode b)
{
return a.val-b.val;
}
});
for(ListNode l:lists)
{
if(l!=null)
{
queue.add(l);
}
}
ListNode result=new ListNode(0);
ListNode cur=result;
while(!queue.isEmpty())
{
cur.next=queue.poll();
cur=cur.next;
if(cur.next!=null)
{
queue.add(cur.next);
}
}
return result.next;
}
}