2017-10-09 117 views
0

我正在研究黑客等级问题。 重复的字符串 [1]:https://www.hackerrank.com/challenges/repeated-string/problem如何处理javascript中for循环的大量内部?

function main() { 
    var s = readLine(); 
    var n = parseInt(readLine()); 
    var rep = 0; 
    var repArray = [] 

//calculate each case 

    while(repArray.length < n){ 
     for(let j = 0; j < s.length; j++){ 
      if(repArray.length > n){ 
       break; 
     } 
      repArray.push(s[j]) 
     } 
    } 

    for(let a = 0; a < repArray.length; a++){ 
    if(repArray[a] === 'a'){ 
      rep++ 
     } 
    } 
    console.log(rep) 
} 

我接收到错误的输入 一个 万亿

我的代码的输出是 < ---过去几年的GC --->

1836 ms: Mark-sweep 597.4 (605.3) -> 359.7 (368.6) MB, 101.7/0.0 ms [allocation failure] [GC in old space requested]. 
1938 ms: Mark-sweep 359.7 (368.6) -> 359.7 (368.6) MB, 102.3/0.0 ms [allocation failure] [GC in old space requested]. 
2040 ms: Mark-sweep 359.7 (368.6) -> 359.7 (367.6) MB, 101.6/0.0 ms [last resort gc]. 
2142 ms: Mark-sweep 359.7 (367.6) -> 359.7 (367.6) MB, 101.7/0.0 ms [last resort gc]. 

< --- JS堆栈跟踪--->

==== JS堆栈跟踪=========================================

Security context: 0x10178c2cfb51 2: main [/run-N6KBYU8cQzCneXKH0Tbm/solution.js:~30] [pc=0x2859725aec0] (this=0x10178c2e6119) 3: /* anonymous */ [/run-N6KBYU8cQzCneXKH0Tbm/solution.js:21] [pc=0x2859725717e] (this=0x2af8d3a77e81) 4: emitNone(aka emitNone) [events.js:91] [pc=0x28597256c33] (this=0x10178c204381 ,handler=0x2af8d3a78049 ,is...

这段代码的错误是

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 1: node::Abort() [/usr/local/nodejs-binary/bin/node] 2: 0x1098b2c [/usr/local/nodejs-binary/bin/node] 3: v8::Utils::ReportApiFailure(char const*, char const*) [/usr/local/nodejs-binary/bin/node] 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/nodejs-binary/bin/node] 5: v8::internal::Factory::NewUninitializedFixedArray(int) [/usr/local/nodejs-binary/bin/node] 6: 0xc4553f [/usr/local/nodejs-binary/bin/node] 7: v8::internal::Runtime_GrowArrayElements(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/nodejs-binary/bin/node] 8: 0x285971079a7

+2

提示:这个问题可以不用实际生成和遍历字符串来解决。 – Quelklef

+0

这个挑战看起来像C,是将C转换成JavaScript的挑战吗? – zer00ne

回答

0

这是找到一个有效的算法有问题。你不能用暴力来解决这类问题。

n有意设置为较高的值,以免您尝试暴力。 10^121 Trillion,即使您可以在one nano second中运行循环的每次迭代,它也会花费1000 seconds,由于不可能在one nano second中运行每次迭代,所以这是很长的。

您面临的问题是由于Space complexity,您试图将(n=10^12)(最大值)字符存储在内存中。如果每个字符占用1 byte随后的内存,我们需要的大小是

10^12 bytes = 1000 Giga bytes = 1 Terra byte 

我敢肯定,你的程序将不会被考虑到内存。鉴于那里一定有其他人试图同时解决这个问题。 Hackerrank不能把这么多的资源给所有人。

问题从未打算让您将此值存储在内存中。意图是你找到一个聪明的解决方法,而不需要存储所有的值。

现在聪明的方法是,你可以统计有多少a s在s。现在,您只需找出有多少个字符串s即可只有n个字符。下面

扰流器(点击/悬停查看答案):

That can be caculated by Math.floor(n/s.length) . Now there may be some remaining string at the end which has length n % s.length . So the solution would be count = Math.floor(n/s.length) * CountAsIn(s) + CountAsIn(s.substring(n % s.length))