// 最大堆(默认)
class PriorityQueue extends SplPriorityQueue {
public function compare($priority1, $priority2) {
return $priority1 - $priority2;
}
}
// 最小堆
class PriorityQueue extends SplPriorityQueue {
public function compare($priority1, $priority2) {
return $priority2 - $priority1;
}
}
例题
答案
优先队列
将多个链表头部放入优先队列
每次取出最小值,再将头部去除,放入优先队列
直到优先队列为空
var mergeKLists = function(lists) {
const priorityQueue = new PriorityQueue(lists.filter(v => v), (a, b) => a.val - b.val)
let r = p = new ListNode()
while (priorityQueue.isEmpty() === false) {
p.next = priorityQueue.pop()
if (p.next.next) priorityQueue.push(p.next.next)
p = p.next
}
return r.next
};
func mergeKLists(lists []*ListNode) *ListNode {
priorityQueue, p := &PriorityQueue{
compare: func(l1 *ListNode, l2 *ListNode) int {
return l1.Val - l2.Val
},
}, &ListNode{}
r := p
for _, list := range lists {
if list != nil {
priorityQueue.Push(list)
}
}
for priorityQueue.IsEmpty() == false {
p.Next = priorityQueue.Pop()
if p.Next.Next != nil {
priorityQueue.Push(p.Next.Next)
}
p = p.Next
}
return r.Next
}
class PriorityQueue extends SplPriorityQueue {
public function compare($priority1, $priority2) {
return $priority2 - $priority1;
}
}
class Solution {
function mergeKLists($lists) {
$r = $p = new ListNode();
$priorityQueue = new PriorityQueue();
$priorityQueue->setExtractFlags(SplPriorityQueue::EXTR_DATA);
foreach ($lists as $list) {
if ($list) $priorityQueue->insert($list, $list->val);
}
while ($priorityQueue->valid()) {
$p->next = $priorityQueue->top();
if ($p->next->next) $priorityQueue->insert($p->next->next, $p->next->next->val);
$p = $p->next;
$priorityQueue->next();
}
return $r->next;
}
}