mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-09 23:16:39 +08:00
fix(javascript): merge-k-sorted-lists (#1575)
This commit is contained in:
@ -39379,20 +39379,21 @@ var mergeKLists = function(lists) {
|
|||||||
let dummy = new ListNode(-1);
|
let dummy = new ListNode(-1);
|
||||||
let p = dummy;
|
let p = dummy;
|
||||||
// 优先级队列,最小堆
|
// 优先级队列,最小堆
|
||||||
let pq = new PriorityQueue(
|
let pq = new PriorityQueue({
|
||||||
lists.length, (a, b) => (a.val - b.val));
|
compare: (a, b) => (a.val - b.val)
|
||||||
|
});
|
||||||
// 将 k 个链表的头结点加入最小堆
|
// 将 k 个链表的头结点加入最小堆
|
||||||
for (let head of lists) {
|
for (let head of lists) {
|
||||||
if (head != null)
|
if (head != null)
|
||||||
pq.add(head);
|
pq.enqueue(head);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (!pq.isEmpty()) {
|
while (!pq.isEmpty()) {
|
||||||
// 获取最小节点,接到结果链表中
|
// 获取最小节点,接到结果链表中
|
||||||
let node = pq.poll();
|
let node = pq.dequeue();
|
||||||
p.next = node;
|
p.next = node;
|
||||||
if (node.next != null) {
|
if (node.next != null) {
|
||||||
pq.add(node.next);
|
pq.enqueue(node.next);
|
||||||
}
|
}
|
||||||
// p 指针不断前进
|
// p 指针不断前进
|
||||||
p = p.next;
|
p = p.next;
|
||||||
|
Reference in New Issue
Block a user