Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Javascript数组#移位或数组#切片会导致性能问题?_Javascript_Arrays_Performance - Fatal编程技术网

为什么Javascript数组#移位或数组#切片会导致性能问题?

为什么Javascript数组#移位或数组#切片会导致性能问题?,javascript,arrays,performance,Javascript,Arrays,Performance,我一直在解决这个问题。它的想法是在第一个索引n次时将元素“向左”移动。问题是当我的算法接收到一个大数组时。在黑客等级服务器中产生超时问题。我不理解这个问题背后的问题。 有人知道会发生什么吗? 我试过两个主意 示例输入 5 4 1 2 3 4 5 示例输出 5 1 2 3 4 想法1 function processData(input) { var input_arguments = input.split(/\n/), rotations_count = parse

我一直在解决这个问题。它的想法是在第一个索引n次时将元素“向左”移动。问题是当我的算法接收到一个大数组时。在黑客等级服务器中产生超时问题。我不理解这个问题背后的问题。 有人知道会发生什么吗?

我试过两个主意

示例输入

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(' '));
}

您试图一个接一个地进行转换,但是一个有效的解决方案会同时进行一次大的转换。您缺少的“问题”是,移位的数量告诉您可以在数组中的什么位置将其“切割”为两个,然后您可以将第一个部分添加到第二个部分的末尾。以他们为例:

let array = [1, 2, 3, 4, 5];
let shifts = 4;

// Create a temp array holding the values of 'array' up the shift point
let temp = array.slice(0, shifts);

// Delete the beginning of 'array' up to shift point
// and add the temp array to the end of 'array'
let newArray = array.splice(shifts).concat(temp);

这就是问题的全部。

首先,您输入了一个打字错误,并使用了
splice
而不是
slice
。使用
slice
shift
d次的解决方案的复杂性为
O(dn)
。你应该能够把这个问题归结到
O(n)
。根据Hackerrank上给出的“限制条件”,这意味着在最坏的情况下,坏的解决方案会慢10000倍。感谢您的指导。现在这个挑战听起来更有趣了!:DHint:不要在任何位置创建新数组all@Bergi实际上,他们可以创建一个新数组来保存结果,但只需将移位作为一次性操作就可以了。好吧,但是如果
shift
是400呢?顺便说一下,这个代码不起作用。它返回
[5,5]
。我想你忘了
splice
返回删除的元素。抱歉,修复了输入错误。它现在应该返回正确的结果。使用此解决方案,
移位的大小
没有意义。您使用本机方法一次剪切和压缩所有数组,而不是使用循环一次剪切和压缩一个数组。我已经用这个精确的解决方案通过了对HackerRank的挑战。也许有一个更有效的解决方案,但这一个对我有效。我不知道HackerRank在使用什么测试,但392的
移位
应该有效,但对你的解决方案无效。@torazaburo我明白你的意思-这超出了这个挑战的范围,因为移位的大小受到限制,它必须始终小于数组的大小(请参阅链接的顶部部分)。你不能像你所想的那样不断地“切换”阵列。对于这种类型的问题,它不起作用,因为
slice()
正在从0调用到大于数组长度的数字。我看不到这种约束。一定是遗漏了什么。