其他分享
首页 > 其他分享> > LeetCode每日一练【23】

LeetCode每日一练【23】

作者:互联网

Merge K Sorted Lists

我的解题

介绍

差强人意的解法, 虽然勉强可以接受, 但是 400ms 左右的运行时间和 70 mb 的内存使用, 还是让人很难接受!

思路

参考: https://www.cnblogs.com/mapodoufu/p/16218278.html

  1. 同二链表排序的方法相似, 我们可以将二维数组链表看成多个二链表排序的集合, 即不断的进行二链表排序

代码

/*
 * @Author: fox
 * @Date: 2022-05-04 15:24:52
 * @LastEditors: fox
 * @LastEditTime: 2022-05-04 17:12:23
 * @Description: https://leetcode.com/problems/merge-k-sorted-lists/
 */

class ListNode {
    constructor (val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}
/**
 * @description: Runtime: 26.31%  Memory Usage: 5.01%
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
const mergeKLists = (lists) => {
    let res = new ListNode(0)

    for (let list of lists) {
        res = mergeTwoLists(res, new ListNode(0, list))
    }

    return res.next
};

/**
 * @description: 二链表排序
 * @param {*} listnode1 链表1
 * @param {*} listnode2 链表2
 * @return {*} 
 */
const mergeTwoLists = (listnode1, listnode2) => {
    const listnode = new ListNode(0)
    let [pointer, pointer1, pointer2] = [listnode, listnode1.next, listnode2.next]

    while (pointer1 && pointer2) {
        if (pointer1.val < pointer2.val) {
            pointer.next = new ListNode(pointer1.val)
            pointer1 = pointer1.next
        } else {
            pointer.next = new ListNode(pointer2.val)
            pointer2 = pointer2.next
        }
        pointer = pointer.next
    }

    if (pointer1) {
        pointer.next = pointer1
    }

    if (pointer2) {
        pointer.next = pointer2
    }

    return listnode
}

大神解题

思路

  1. 二分法 + 递归 + 二链表排序 (似懂非懂, 喊牛皮就对了!)

代码

/*
 * @Author: fox
 * @Date: 2022-05-04 17:15:00
 * @LastEditors: fox
 * @LastEditTime: 2022-05-04 18:21:19
 * @Description: https://leetcode.com/problems/merge-k-sorted-lists/
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
 function mergeKLists(lists) {
    if(!lists || lists.length === 0) return null; // 如果lists为空 返回null
    
    function devideAndConquer(start, end) { // 二分法
        if(start === end) return lists[start] // 如果lists.length === 1, 直接返回lists[0]
        const mid = Math.floor((start + end) / 2) // 中间索引
        const leftSide = devideAndConquer(start, mid)
        const rightSide = devideAndConquer(mid + 1, end)
        return mergeTwoLists(leftSide, rightSide)
    }
    return devideAndConquer(0, lists.length - 1)
};

/**
 * @description: 递归运算 二链表排序
 * @param {*} list1
 * @param {*} list2
 * @return {*}
 */
function mergeTwoLists(list1, list2) {
    if(!list1) return list2
    if(!list2) return list1
    
    if(list1.val < list2.val) {
        list1.next = mergeTwoLists(list1.next, list2)
        return list1
    } else {
        list2.next = mergeTwoLists(list1, list2.next)
        return list2
    }
}

标签:return,val,23,每日,lists,next,链表,ListNode,LeetCode
来源: https://www.cnblogs.com/mapodoufu/p/16221888.html