题解 | 合并k个已排序的链表

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

class MinHeap {
    constructor() {
        this.heap = [];
    }

    insert(node) {
        this.heap.push(node);
        this.bubbleUp(this.heap.length - 1);
    }

    extractMin() {
        if (this.heap.length === 0) return null;
        if (this.heap.length === 1) return this.heap.pop();

        const minNode = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.bubbleDown(0);

        return minNode;
    }

    isEmpty() {
        return this.heap.length === 0;
    }

    bubbleUp(index) {
        while (index > 0) {
            const parentIndex = Math.floor((index - 1) / 2);
            if (this.heap[index].val < this.heap[parentIndex].val) {
                [this.heap[index], this.heap[parentIndex]] = [
                    this.heap[parentIndex],
                    this.heap[index],
                ];
                index = parentIndex;
            } else {
                break;
            }
        }
    }

    bubbleDown(index) {
        const length = this.heap.length;
        while (true) {
            let smallest = index;
            const leftChildIndex = 2 * index + 1;
            const rightChildIndex = 2 * index + 2;

            if (
                leftChildIndex < length &&
                this.heap[leftChildIndex].val < this.heap[smallest].val
            ) {
                smallest = leftChildIndex;
            }

            if (
                rightChildIndex < length &&
                this.heap[rightChildIndex].val < this.heap[smallest].val
            ) {
                smallest = rightChildIndex;
            }

            if (smallest !== index) {
                [this.heap[index], this.heap[smallest]] = [
                    this.heap[smallest],
                    this.heap[index],
                ];
                index = smallest;
            } else {
                break;
            }
        }
    }
}
function mergeKLists(lists) {
    // write code here
    const heap = new MinHeap();

    // 将每个链表的头节点加入最小堆
    for (let i = 0; i < lists.length; i++) {
        if (lists[i]) {
            heap.insert(lists[i]);
        }
    }

    const dummy = new ListNode(0);
    let current = dummy;

    while (!heap.isEmpty()) {
        const node = heap.extractMin();
        current.next = node;
        current = current.next;

        if (node.next) {
            heap.insert(node.next);
        }
    }

    return dummy.next;
}
module.exports = {
    mergeKLists: mergeKLists,
};

全部评论

相关推荐

牛客227372317号:第一,你在开头写的熟练运用的软件在后面的项目经历中都没有体现。第二,熟练运用电焊,游标卡尺这样的描述可以删去,这样的技能专科生,甚至有点的高中生都会。第三,把教学课程放上面,在项目经历中,要让HR看到你是如何把课程和项目进行结合的,你自己的思考是什么。
点赞 评论 收藏
分享
01-15 17:34
保定学院 Java
数学转码崽:学历没优势就得卷项目和实习啊,但是我看了一下你这个项目,什么雪花算法,搜索引擎,Docker,minio这些都属于通用的东西啊,根本不算亮点,没有任何业务相关性。 还有第二个看到统一鉴权,分片上传估计面试官都不想看了。连我一个偶尔刷刷牛客简历的都看多了,面试官估计早都看吐了。。。 秋招结束了,就尽量找找中小厂吧,毕竟你现在转行已经没时间了,高低有一段实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务