编写一个函数,该函数接受一个值数组,并将所有为零的元素移动到数组末尾,否则保留数组的顺序。零元素还必须保持它们出现的顺序。
零元素由 0 或“0”定义。某些测试可能包含非数字文字的元素。
不允许使用任何临时数组或对象。也不允许使用任何 Array.prototype 或 Object.prototype 方法。因此不允许使用 array.push 或 splice() 。
我试过这个:
function removeZeros(nums) {
for(let i = nums.length - 1; i >= 0 ; i--){
if(nums[i] === 0){
nums.splice(i, 1);
nums.push(0);
}
}
return nums;
}
input:
[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
预期的:
[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
Actual:
[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]
结果是正确的,但我需要在没有 array.push() 或 array.splice() 的情况下执行此操作