[leetcode]23. Merge k Sorted Lists归并k个有序链表

时间:2023-06-30 17:19:10

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6

题意:

归并k个有序链表。

思路:

用一个最小堆minHeap,将所有链表的头结点放入

新建一个linkedlist存储结果

minHeap里面每remove一个node(最小堆保证了该元素为当前堆中最小), 就加到新建linkedlist中,并将该node.next加入到堆里

代码:

 class Solution {
public ListNode mergeKLists(ListNode[] lists) {
// special case
if(lists.length==0) return null; //1. priorityqueue ((o1,o2)-> o1.val, o2.val) acsending order
PriorityQueue<ListNode> heap = new PriorityQueue<>((o1,o2)-> o1.val-o2.val); //add each list's each node into the heap, in acsending order
int size = lists.length;
for(int i = 0; i<size; i++){
if(lists[i]!=null){
heap.add(lists[i]); //注意这步操作直接把list的每个节点都扔进了heap }
}
//2. create a new linkedlist
ListNode fakeHead = new ListNode(-1);
ListNode current = fakeHead; //3. add every node from priorityqueue's removing
while(heap.size()!=0){
ListNode node = heap.remove();
current.next = node;
current=current.next;
if(node.next!=null) heap.add(node.next);
}
return fakeHead.next;
}
}