链表的结构定义如下
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
解法:1. 归并法(分治) 2. 利用优先队列
class Solution {
/**
* 利用优先队列,快速求出当前lists中最小的元素结点
* @param ListNode[] $lists
* @return ListNode
*/
function mergeKLists($lists) {
$myPriQueue = new class extends SplPriorityQueue {
public function compare($priority1, $priority2)
{
return $priority2 - $priority1;
}
};
foreach ($lists as $node) {
if (!is_null($node)) {
$myPriQueue->insert($node, $node->val);
}
}
$head = new ListNode(0);
$prev = $head;
while (!$myPriQueue->isEmpty()) {
$minNode = $myPriQueue->extract();
$prev->next = $minNode;
$prev = $prev->next;
if (!is_null($minNode->next)) {
$minNode = $minNode->next;
$myPriQueue->insert($minNode, $minNode->val);
}
}
return $head->next;
}
/**
* 使用归并的方法
* @param $lists
*/
function mergeKlistV2($lists) {
return $this->merge($lists, 0, count($lists)-1);
}
function merge(&$lists, $l, $r) {
if ($l == $r) {
return $lists[$l];
}
if ($l > $r) {
return null;
}
$mid = $l + intdiv($r-$l, 2);
return $this->mergeTwoLists($this->merge($lists, $l, $mid), $this->merge($lists, $mid+1, $r));
}
function mergeTwoLists($node1, $node2) {
$head = new ListNode(0);
$prev = $head;
while ($node1 && $node2) {
if ($node1->val < $node2->val) {
$prev->next = $node1;
$node1 = $node1->next;
} else {
$prev->next = $node2;
$node2 = $node2->next;
}
$prev = $prev->next;
}
$node1 ? $prev->next = $node1 : $prev->next = $node2;
return $head->next;
}
}