猿问

合并两个列表 LeetCode

我已经在 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 ListNode

Line 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;

};

我真的不知道问题出在哪里......如果有人可以帮助我将不胜感激


慕仙森
浏览 875回答 1
1回答

MM们

这是一个链接列表合并问题,而不是常规数组合并。这会通过:/**&nbsp;* Definition for singly-linked list.&nbsp;* function ListNode(val, next) {&nbsp;*&nbsp; &nbsp; &nbsp;this.val = (val===undefined ? 0 : val)&nbsp;*&nbsp; &nbsp; &nbsp;this.next = (next===undefined ? null : next)&nbsp;* }&nbsp;*//**&nbsp;* @param {ListNode} l1&nbsp;* @param {ListNode} l2&nbsp;* @return {ListNode}&nbsp;*/var mergeTwoLists = function(l1, l2) {&nbsp; &nbsp; var dummy = {&nbsp; &nbsp; &nbsp; val : -1,&nbsp; &nbsp; &nbsp; next : null&nbsp; &nbsp; };&nbsp; &nbsp; var curr = dummy;&nbsp; &nbsp; while (l1 && l2) {&nbsp; &nbsp; &nbsp; &nbsp; if (l1.val > l2.val) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; curr.next = l2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l2 = l2.next;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; curr.next = l1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l1 = l1.next;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; curr = curr.next;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; curr.next = l1 || l2;&nbsp; &nbsp; return dummy.next;};这就是您的列表的样子:/**&nbsp;* Definition for singly-linked list.&nbsp;* function ListNode(val, next) {&nbsp;*&nbsp; &nbsp; &nbsp;this.val = (val===undefined ? 0 : val)&nbsp;*&nbsp; &nbsp; &nbsp;this.next = (next===undefined ? null : next)&nbsp;* }&nbsp;*//**&nbsp;* @param {ListNode} l1&nbsp;* @param {ListNode} l2&nbsp;* @return {ListNode}&nbsp;*/
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答