javascript - 合并两个列表 LeetCode

标签 javascript node.js

我已经在 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;
};
我真的不知道问题出在哪里...如果有人可以帮助我将不胜感激

最佳答案

这是一个 Linked List 合并问题,而不是常规数组合并。这会通过:

/**
 * 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}
 */

引用
  • 有关更多详细信息,您可以查看 Discussion Board 。有很多公认的解决方案,其中包含各种 languages 和解释、高效算法以及渐近 time/space 复杂性分析 12

  • 如果您正在为 interviews 做准备:
  • We'd write bug-free and clean codes based on standards and conventions (e.g., 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 1 , 1 , 1 ).
  • 关于javascript - 合并两个列表 LeetCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62857939/

    相关文章:

    javascript - 完全自动化传递作为开发 pull 请求确认的一部分

    javascript - dotenv API 凭证字符串或不带引号的

    node.js - express 是否解决了 "blocking code"问题?

    javascript - 需要部分 JavaScript 文件的内存使用情况

    node.js - 从具有相同跟踪 ID 的代码中调用 lambda?

    javascript - 使用 CSS 使图像变暗

    javascript - 从第一个下拉列表中选择后,如何将 li 值填充到另一个下拉列表中?

    javascript - AJAX/Javascript 在 PHP 中页面加载时选择元素更改

    javascript - 无法通过 gulp 实现 Bower 自动化

    node.js - Electron 应用程序的基本调试