合并K个升序链表题解

题目链接
23. 合并 K 个升序链表 - 力扣(LeetCode)

题解:

  1. 首先特判------数组长度为0的 返回null ,长度为1的返回 lists0

  2. 对于这题,我们先首先记录,每个列表的第一个元素,维护这个数组,我们后续每次都从这个数组里面挑选最小值,来作为新链表的 下一个元素 ,如果当前下标的 数组被采用,则 往后走,链表往后走,无非就是先记录下一个的值,然后替换掉 我们维护的数组 当前位置的元素。

  3. 需要特别判断 数组元素为null的情况(其实也可以在 第一次就预处理了)

  4. 用一个循环来 不停找最小值,对于出现每一次null的情况,我们用count计数,出现一次null的情况,count--,代表这个链表已经走完,直到count为0,说明循环该结束了,返回答案即可

代码:

javascript 复制代码
// 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.length === 0) return null
    if (lists.length === 1) return lists[0]

    let res = null

    let curArr = [], count = lists.length, head = null
    // 头节点
    for (let i = 0; i < lists.length; i++) {
        curArr.push(lists[i])
    }

    function getMin(nodes) {
        let min = Number.MAX_SAFE_INTEGER, nodePos = 0
        for (let i = 0; i < nodes.length; i++) {
            // console.log(nodes[i].val)
            if (nodes[i] && min > nodes[i].val) {
                nodePos = i
                min = nodes[i].val
            }
        }
        return nodePos
    }

    while (count) {
        let pos = getMin(curArr)

        if (curArr[pos] === null) {
            count--
            continue
        }

        if (res === null) head = res = curArr[pos]
        else {
            res.next = curArr[pos]
            res = curArr[pos]
        }
        let t = res.next
        res.next = null
        if (t !== null) curArr[pos] = t
        else {
            count--
            curArr[pos] = null
        }
    }

    return head
};
相关推荐
Emily156853598703 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
To_OC8 小时前
面试被问了三回三栏布局,这次我终于把 BFC 那层窗户纸捅破了
前端·css·面试
小飞学编程...8 小时前
【哈希表】
数据结构·哈希算法·散列表
To_OC9 小时前
啃完 TS 工具类型我发现:Pick 和 Omit 原来就是一层窗户纸
前端·面试·typescript
风月说与山鬼10 小时前
三、大括号语法
前端·react.js
kyriewen10 小时前
我把最常踩的8个CORS跨域报错整理了一遍——第8个去年还不存在
前端·javascript
Csvn11 小时前
🕰️ 闭包 + setTimeout 的 5 个经典陷阱:为什么定时器看到的永远不是最新的值?
前端
重生之后端学习11 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
lilian23311 小时前
Harmony os 技术实战|拼豆制图27:用单字符编码承载 50 张 70×70 图纸
前端·数据库·华为·harmonyos