Shu-How Zの小窝

Loading...

LeetCode:23.合并K个排序链表

LeetCode:23.合并K个排序链表

解题思路新链表的下一个节点一定是k个链表头中的最小节点。考虑选择使用最小堆。

解题步骤构建一个最小堆,并依次把链表头插入堆中。弹出堆顶接到输出链表,并将堆顶所在链表的新链表头插入堆中。等堆元素全部弹出,合并工作就完成了。

class MinHeap {
    constructor() {
      this.heap = []
      this.len = 0
    }
    size() {
      return this.len
    }
    push(val) {
      this.heap[++this.len] = val
      this.swin(this.len)
    }
  
    pop() {
      if(this.top()===1) return this.heap.shift(1);
      const ret = this.heap[1]
      this.swap(1, this.len--)
      this.heap[this.len + 1] = null
      this.sink(1)
      return ret
    }
    swin(ind) {
      while (ind > 1 && this.less(ind, parseInt(ind / 2))) {
        this.swap(ind, parseInt(ind / 2))
        ind = parseInt(ind / 2)
      }
    }
    sink(ind) {
      while (ind * 2 <= this.len) {
        let j = ind * 2
        if (j < this.len && this.less(j + 1, j)) j++
        if (this.less(ind, j)) break
        this.swap(ind, j)
        ind = j
      }
    }
    top() {
      return this.heap[1]
    }
    isEmpty() {
      return this.len === 0
    }
  
    swap(i, j) {
      [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]
    }
    less(i, j) {
      return this.heap[i].val < this.heap[j].val
    }
    getHeap() {
      return this.heap
    }
  }
/**
 * 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) {
    if(!lists) return;
    let root=new ListNode(0);
    let h=new MinHeap()
    lists.forEach(n=>n&&h.push(n))
    let n;
    let p=root
    while(h.size()){
        n=h.pop();
        p.next=n
        p=p.next
        if(n.next)h.push(n.next)
    }
    return root.next
};

'

posted @ 2025-01-14 22:58  KooTeam  阅读(12)  评论(0)    收藏  举报