我一直在解決a hacker rank problem。它的想法是「向左」移動第一個索引元素n次。問題是當我的算法收到一個大數組時。在黑客等級服務器中產生超時問題。我不明白這個問題背後的問題。 任何人都知道發生了什麼?爲什麼JavaScript Array#shift或Array#slice會導致性能問題?
我試圖兩個想法
示例輸入
5 4
1 2 3 4 5
實施例輸出
5 1 2 3 4
思想1
function processData(input) {
var input_arguments = input.split(/\n/),
rotations_count = parseInt(input_arguments[0].split(/\s/)[1],10),
array = input_arguments[1].split(/\s/);
while(rotations_count--){
let value = array[0];
array = array.slice(1);
array.push(value);
}
console.log(array.join(' '));
}
Idea2
function processData(input) {
var input_arguments = input.split(/\n/),
rotations_count = parseInt(input_arguments[0].split(/\s/)[1],10),
array = input_arguments[1].split(/\s/);
while(rotations_count > 0){
array.push(array.shift());
rotations_count--;
}
console.log(array.join(' '));
}
首先,你犯了一個錯字,並使用'splice'而不是'slice'。 – Bergi
使用'slice'或'shift'的時間解決方案的複雜度爲'O(d n)'。你應該能夠把它歸結爲'O(n)'。根據Hackerrank給出的「約束條件」,這意味着在最糟糕的情況下,不好的解決方案會慢10000倍。 – Bergi
感謝您的指導。現在挑戰聽起來非常有趣! :D –