合并K个升序链表题解

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

题解:

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

  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
};
相关推荐
jianfeng_zhu17 分钟前
整数数组匹配
数据结构·c++·算法
yueqingll25 分钟前
032、数据结构之代码时间复杂度和空间复杂度的判断:从入门到实战
数据结构
jlspcsdn1 小时前
20251222项目练习
前端·javascript·html
行走的陀螺仪1 小时前
Sass 详细指南
前端·css·rust·sass
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 小时前
React 怎么区分导入的是组件还是函数,或者是对象
前端·react.js·前端框架
LYFlied1 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
子春一21 小时前
Flutter 2025 国际化与本地化工程体系:从多语言支持到文化适配,打造真正全球化的应用
前端·flutter
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之file命令(实操篇)
linux·运维·前端·网络·chrome·笔记
羽沢313 小时前
ECharts 学习
前端·学习·echarts