为什么我在 Javascript 中收到错误“Output Limit Exceeded”?

问题描述 投票:0回答:1

我正在尝试用javascript语言解决leetcode上的

LinkedList
问题,但在
86
测试用例中
74
案例已通过,但在
75
我收到错误
Output Limit Exceeded

问题:

Given the head of a singly linked list, return true if it is a palindrome.

示例:

Input: head = [1,2,2,1]
Output: true

Input: head = [1,2]
Output: false

我的代码:

let array = [];
let list = head;
while (list) {
  array.push(list.val)
  console.log("array1", array)
  list = list.next;
}

let list2 = head;
while (list2) {
  let out = array.pop()
  if (out === list2.val) {
    list2 = list2.next;
  } else {
    return false
  }
}

return true

Last executed input:
[3,8,9,3,2,8,9,1,8,9,9,8,5,2,5,4,4,4,3,9,7,5,0,5,8 ,6,3,3,8,0,7,3,7,7,1,1,1,7,0,2,8,1,8,7,2,9,5,2,9,7 ,4,8,...]

我不明白为什么我会得到

Limit exceeded error
?是不是因为输入太多了?或者问题出在我的代码中?如果问题出在输入上,那么我如何在 Javascript 中解决这个问题?

javascript arrays linked-list palindrome
1个回答
3
投票

console.log
被 LeetCode 框架捕获,该框架对可以生成的输出的总大小设置了限制。当您的第一个循环在 every 迭代中调用它时,每次都会打印已收集值的数组,您将按照 3𝑛(𝑛+1)/2 个字符的顺序生成输出。完整的测试套件将进行 𝑛 高达 105 的测试,这意味着您可以生成超过 150 亿个字符。 LeetCode 会在脚本执行到此之前停止它。

另请注意,生成调试输出会显着减慢进程速度,因此您还面临着达到时间限制的风险。

只需删除

console.log
即可。

作为后续:尝试找到一种解决方案,不要将每个值复制到数组中,这需要 O(n) 额外空间。相反,尝试使用 O(1) 额外空间来完成此操作。

© www.soinside.com 2019 - 2024. All rights reserved.