JavaScript实现 - LeetCode刷题 -【合并K个升序链表】- 第 23 题 !!!

题目:

LeetCode题目链接

题目截图:

LeetCode刷题

解题步骤:

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)

怎么样,是不是很简单,你学会了吗 ?

LeetCode刷题

LeetCode刷题

如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪 !!!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值