gpt4 book ai didi

javascript - 如何在数组的开头移动所有零项?

转载 作者:行者123 更新时间:2023-12-01 15:38:13 24 4
gpt4 key购买 nike

我正在尝试解决 O(n) 中的问题没有 taking space (如对象图)。我想在开头移动所有零,一个在最后一个,两个在中间。
输入 : [0, 1, 0, 2, 1]
预期产量 : [0,0,2,1,1]
这是我的代码

let arr = [0, 1, 0, 2, 1];

function swap(input, i, j) {
let temp = input[i];
input[j] = input[i];
input[i] = temp;
}

function moveZeroOneAndTwo(input) {
let i = 0,
j = input.length - 1;
while (i < j) {
while (arr[i] !== 0) i++;
while (arr[j] !== 0) j--;

swap(arr, j, i);
i++;
j--;
}

return input
}

console.log(moveZeroOneAndTwo(arr))
我正在寻找 1左起索引和 zero来自 right 的索引并交换它们仍然无法解决这个问题

最佳答案

计算 0,1,2,然后用 3 个值及其从一开始的计数填充数组。
您不需要任何额外的 var-space,只需使用原始数组。

let arr = [0, 1, 0, 2, 1];
let count = [0,0,0];
arr.forEach(el => count[el]++);
arr.fill(0,0,count[0]);
arr.fill(2,count[0],count[0]+count[2]);
arr.fill(1,count[0]+count[2],count[0]+count[1]+count[2]);
console.log(arr);

关于javascript - 如何在数组的开头移动所有零项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63484442/

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