V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
TomVista
V2EX  ›  问与答

leetcod 内存溢出

  •  
  •   TomVista · 2019-05-24 15:16:39 +08:00 · 914 次点击
    这是一个创建于 1791 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请无视我的解题思路,算法一点都不懂. 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

    var mergeTwoLists = function(l1, l2) {
        var array =[];
        
        if(l1===null){
            return l2;
        }
        if(l2===null){
            return l1;
        }
        
        array.push(l1);
        while(array[array.length-1].next !== null){
            array.push(array[array.length-1].next);
        }
        
        array.push(l2);
        while(array[array.length-1].next !== null){
            array.push(array[array.length-1].next);
        }
        
        array.sort(function(a,b){
            return a.val-b.val;
        });
        
        for(var i=0;i<array.length-1;i++){
            array[i].next = array[i+1]
        }
        
        return array[0];
        
    };
    

    下面这一组测试会造成内存溢出 [-10,-9,-7,-1,-1,3,3,7,7] [-6,-4,1,1,2,6], 我用其他 更长的测试反而不会溢出 [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10] [-6,-4,1,1,2,6]

    2 条回复    2019-05-25 10:31:33 +08:00
    KHHj7U2DNR
        1
    KHHj7U2DNR  
       2019-05-25 01:37:08 +08:00 via Android
    试试在 return 语句之前加一句 "array[array.length-1].next = null" ?
    TomVista
        2
    TomVista  
    OP
       2019-05-25 10:31:33 +08:00
    厉害了 @KHHj7U2DNR
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3410 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 11:30 · PVG 19:30 · LAX 04:30 · JFK 07:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.