0
点赞
收藏
分享

微信扫一扫

23. 合并K个升序链表 字节跳动最爱考的 64 道算法题 (1)


题目来自:​​字节跳动最爱考的 64 道算法题(JS版) - 掘金​​

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1:

输入:lists = [[1,4,5],[1,3,4],[2,6]]

输出:[1,1,2,3,4,4,5,6]

解释:链表数组如下:

[

  1->4->5,

  1->3->4,

  2->6

]

将它们合并到一个有序链表中得到。

1->1->2->3->4->4->5->6

示例 2:

输入:lists = []

输出:[]

示例 3:

输入:lists = [[]]

输出:[]


提示:

k == lists.length

0 <= k <= 10^4

0 <= lists[i].length <= 500

-10^4 <= lists[i][j] <= 10^4

lists[i] 按 升序 排列

lists[i].length 的总和不超过 10^4

通过次数396,867提交次数702,383

商业载请联系官方授权,非商业转载请注明出处

var mergeKLists = function(lists) {
let head = new ListNode(-1);
p = head
const h = new MinHeap()
lists.forEach(i => {
if (i) {
h.insert(i)
}
})
while(h.size()) {
let node = h.pop()
p.next = node;
p = p.next
if (node.next) {
h.insert(node.next)
}
}
return head.next
};


class MinHeap {
constructor() {
this.heap = []
}
getParentIndex(index) {
return (index - 1) >> 1
}
getLeftIndex(index) {
return index * 2 + 1
}
getRightIndex(index) {
return index * 2 + 2;
}
insert(node) {
this.heap.push(node);
this.shiftUp(this.heap.length - 1)
}
swap(a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
pop() {
if(this.size() === 1) return this.heap.shift()
const top = this.heap[0]
// pop()方法删除数组最后一个元素并返回,赋值给堆顶
this.heap[0] = this.heap.pop();
// 对堆顶重新排序
this.shiftDown(0);
return top
}
shiftUp(index) {
if (index === 0) return; //
let parent = this.getParentIndex(index);
if (this.heap[parent].val > this.heap[index].val) {
this.swap(parent, index);
this.shiftUp(parent)
}
}
shiftDown(index) {
let left = this.getLeftIndex(index);
let right = this.getRightIndex(index);
if (this.heap[left] && this.heap[index].val > this.heap[left].val ) {
this.swap(left, index);
this.shiftDown(left)
}
if (this.heap[right] && this.heap[index].val > this.heap[right].val ) {
this.swap(right, index);
this.shiftDown(right)
}
}
size() {
return this.heap.length
}
}


举报

相关推荐

0 条评论