力扣打卡:23. 合并K个升序链表 | 链表 | 合并链表

题目

力扣打卡:23. 合并K个升序链表

解题思路

  • 暴力解法

遍历链表数组,合并每一条链表

  • 两两合并法

遍历数组链表元素,合并其中的两个,不再是单独合并一个
注意:如果需要原有的数组,那么需要注意数组长度的使用应该是新长度;如果是构建新数组使用则无此问题

代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 * 通过优先级队列实现,或者是通过合并两个链表实现
 * 一个一个链表的合并可以实现功能的需求,而合并两个则是可以降低时间复杂度
 * 将多个链表的合并问题分解到两个链表的合并,每一个新合成的链表与下一个链表进行合并
 */
function mergeKLists1(lists: Array<ListNode | null>): ListNode | null {
    let res = null
    for (const head of lists) {
        res = merge2Lists(res, head)
    }
    return res
};

function merge2Lists(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    if (l1 === null) return l2;
    if (l2 === null) return l1;
    if (l1.val <= l2.val) {
        l1.next = merge2Lists(l1.next, l2);
        return l1;
    } else {
        l2.next = merge2Lists(l1, l2.next);
        return l2;
    }
}

// 通过两两合并降低时间复杂度,定义规则
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
    let len: number = lists.length;
    if (len === 0) return null
    while (len > 1) {
        let idx = 0; // 保持原有数组的复用
        for (let i = 0; i < len; i += 2) {
            if (i === len - 1) lists[idx++] = lists[i]; // 注意使用新长度
            else lists[idx++] = merge2Lists(lists[i], lists[i + 1])
        }
        len = idx // 新长度的赋值
    }
    return lists[0];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值