题目:
题目截图:
解题步骤:
1.构建一个最小堆,并依次把链表头插入堆中,但需要对最小堆有所改动
2.弹出最小的堆顶接到输出链表,并将之前弹出的堆顶所在链表的新链表头,插入堆中
3.重复第二步,等堆元素全部弹出,合并工作就完成了
代码:
// 最小堆
class MinHeap {
constructor() {
this.heap = [];
}
// 交换
swap(i1, i2) {
const temp = this.heap[i1];
this.heap[i1] = this.heap[i2];
this.heap[i2] = temp;
}
// 获取父节点下标
getParentIndex(i) {
return (i - 1) >> 1;
}
// 获取左子节点下标
getLeftIndex(i) {
return i * 2 + 1;
}
// 获取右子节点下标
getRightIndex(i) {
return i * 2 + 2;
}
// 上移操作
shiftUp(index) {
if (index === 0) return;
const parentIndex = this.getParentIndex(index);
if (this.heap[parentIndex] && this.heap[parentIndex].val > this.heap[index].val) {
this.swap(parentIndex, index);
this.shiftUp(parentIndex);
}
}
// 下移操作
shiftDown(index) {
const leftIndex = this.getLeftIndex(index);
const rightIndex = this.getRightIndex(index);
if (this.heap[leftIndex] && this.heap[leftIndex].val < this.heap[index].val) {
this.swap(leftIndex, index);
this.shiftDown(leftIndex);
}
if (this.heap[rightIndex] && this.heap[rightIndex].val < this.heap[index].val) {
this.swap(rightIndex, index);
this.shiftDown(rightIndex);
}
}
// 插入元素
insert(value) {
this.heap.push(value);
this.shiftUp(this.heap.length - 1);
}
// 删除堆顶元素
pop() {
if (this.size() === 1) return this.heap.shift();
const top = this.heap[0];
this.heap[0] = this.heap.pop();
this.shiftDown(0);
return top;
}
// 获取堆顶元素
peek() {
return this.heap[0];
}
// 获取堆的大小
size() {
return this.heap.length;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function (lists) {
const res = new ListNode(0);
let p = res;
const h = new MinHeap();
lists.forEach(l => {
if (l) h.insert(l);
});
while (h.size()) {
const n = h.pop();
p.next = n;
p = p.next;
if (n.next) h.insert(n.next);
}
return res.next;
};
时间复杂度分析:
时间复杂度是O(n logk),n是所有链表的节点数之和,k是k个链表
空间复杂度分析:
空间复杂度是O(k)
怎么样,是不是很简单,你学会了吗 ?
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪 !!!