gpt4 book ai didi

Javascript数组末尾追加0

转载 作者:行者123 更新时间:2023-11-28 12:18:55 24 4
gpt4 key购买 nike

我正在解决这个问题

Given an array of numbers, I need to move all zeros at the end of thearray (in-place without making a copy of an array)

For example: given nums = [0, 1, 0, 3, 12]

After calling yourfunction, nums should be [1, 3, 12, 0, 0].

我的尝试:

   var moveZeroes = function(nums) {
var count=0;

//Remove anything that's not Zero.
nums.forEach(function(val, index){
if(val==0){
nums.splice(index, 1);
count++;
}
});

//Fill in Zeros at the end
for(var i=0; i< count ; i++){
nums.push(0);
}
};


var input1 = [0,1,0,3,12];
var input2 = [0,0,1];

moveZeroes(input1)
console.log(input1); //Works!

moveZeroes(input2)
console.log(input2); //fails!

问题:

它适用于诸如 [0,1,0,3,12] 之类的输入,但在诸如 [0,0,1] 之类的输入中失败(输出我得到的是 0,1,0);为什么?我该如何修复它?

最佳答案

您从当前正在循环的数组中剪切(拼接)(在forEach中),因此有更多连续的0 其中一些将被跳过。

因此,如果数组是[0, 0, 1],则会发生以下情况:

forEach: (case of two or more successive 0s)

[0, 0, 1]
// ^ cursor is here (0 === 0 then remove it)
[0, 1]
// ^ cursor is at the second item, the second 0 is safe because it is now occupy a place that is already looped over
[0, 1]
// fails

forEach: (case of no successive 0s)

[0, 1, 0, 1]
// ^ cursor is here (0 === 0 then remove it)
[1, 0, 1]
// ^ (0 === 0 then remove)
[1, 1]
// works

要解决这个问题,您必须使用基本的 for 循环,您可以在其中控制光标(索引)的位置,或者以不改变其长度的方式更改数组并且不将 0 隐藏在光标后面,如下所示:

var moveZeroes = function(nums) {
nums.forEach(function(val, index) {
if (val) { // if it is a non-zero value
nums.splice(index, 1); // remove it
nums.unshift(val); // add it to the begining of the array (note that the order of non-zero values will be reversed)
}
});
};


var input1 = [0, 1, 0, 3, 12];
var input2 = [0, 0, 1];

moveZeroes(input1)
console.log(input1); //Works!

moveZeroes(input2)
console.log(input2); // Now Works too!

关于Javascript数组末尾追加0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42869120/

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