gpt4 book ai didi

javascript - 合并两个列表 LeetCode

转载 作者:行者123 更新时间:2023-12-04 12:23:57 28 4
gpt4 key购买 nike

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

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com