亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

合并兩個列表 LeetCode

合并兩個列表 LeetCode

慕仙森 2022-11-11 16:34:39
我已經在 Repl.it 網站上解決了這個問題,但是當我在 LeetCode 上提交代碼時,它給出了一個 typeError,我將把它粘貼在這里:Line 29 in solution.js         throw new TypeError(__serialize__(ret) + " is not valid value for the expected return type ListNode");         ^TypeError: [] is not valid value for the expected return type ListNodeLine 29: Char 20 in solution.js (Object.<anonymous>)Line 16: Char 8 in runner.js (Object.runner)Line 13: Char 26 in solution.js (Object.<anonymous>)Line 1200: Char 30 in loader.js (Module._compile)Line 1220: Char 10 in loader.js (Object.Module._extensions..js)Line 1049: Char 32 in loader.js (Module.load)Line 937: Char 14 in loader.js (Function.Module._load)at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)Line 17: Char 47 in run_main_module.js這是代碼:var mergeTwoLists = function(l1, l2) {  let i = 0, j = 0;  var out = [];  while(i < l1.length || j < l2.length) {    if(j == l2.length || i < l1.length && l1[i] < l2[j]) {      out.push(l1[i++]);    } else {      out.push(l2[j++]);    }  }  return out;};我真的不知道問題出在哪里......如果有人可以幫助我將不勝感激
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

這是一個鏈接列表合并問題,而不是常規數組合并。這會通過:


/**

 * Definition for singly-linked list.

 * function ListNode(val, next) {

 *     this.val = (val===undefined ? 0 : val)

 *     this.next = (next===undefined ? null : next)

 * }

 */

/**

 * @param {ListNode} l1

 * @param {ListNode} l2

 * @return {ListNode}

 */

var mergeTwoLists = function(l1, l2) {

    var dummy = {

      val : -1,

      next : null

    };

    var curr = dummy;

    while (l1 && l2) {

        if (l1.val > l2.val) {

            curr.next = l2;

            l2 = l2.next;

        } else {

            curr.next = l1;

            l1 = l1.next;

        }

        curr = curr.next;

    }

    

    curr.next = l1 || l2;


    return dummy.next;

};

這就是您的列表的樣子:


/**

 * Definition for singly-linked list.

 * function ListNode(val, next) {

 *     this.val = (val===undefined ? 0 : val)

 *     this.next = (next===undefined ? null : next)

 * }

 */

/**

 * @param {ListNode} l1

 * @param {ListNode} l2

 * @return {ListNode}

 */

查看完整回答
反對 回復 2022-11-11
  • 1 回答
  • 0 關注
  • 847 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號