链表的结构定义如下
/**
* 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;
}
}

这篇博客介绍了如何高效地合并多个已排序的链表。作者提出了两种方法:一是利用优先队列(堆)实现,通过比较链表节点的值来快速找到最小节点并进行合并;二是采用归并排序的思想,递归地将链表两两合并。这两种方法都实现了将多个链表合并为一个有序链表的功能。


被折叠的 条评论
为什么被折叠?



