You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
DarthVaderrr, chongjohn716, zhengchangshun, IsaacZhanghw, laoboxie and 5 morejwei921118, xiaoheshangnmsl, zhouyec, yuanxiang1990 and aksaberhyy126wingmeng, Robbie-Han, jjeejj, a958330481, wwwjun and 8 more
Activity
ChuYang-FE commentedon May 27, 2019
新增:解决了有连续的0无法实现功能的问题。
Rashomon511 commentedon May 27, 2019
y1324 commentedon May 27, 2019
let nums = [0,1,0,3,12];
fengjinlong commentedon May 27, 2019
let arr = [1,2,3,0,7,0]
j = arr.length
for (i = 0; i < j; i++) {
if (arr[i] === 0) {
arr.splice(i,1)
arr.push(0)
}
}
btea commentedon May 27, 2019
wingmeng commentedon May 27, 2019
已修正连续多个 0 时的 bug
思路:用一个
len
记录 0 的出现次数,再过滤掉原数组中所有的 0,最后在数组末尾补上被移除的 0jjeejj commentedon May 27, 2019
上面所有的再循环中,先 splice 在 push 的方法都是有问题的
因为,当
splice
一个元素的时候,紧跟着的后面一个元素会向前移动一位,索引会变成正在删除那个元素的,所有当有连续的 0 时候,无法满足要求wz71014q commentedon May 27, 2019
Hunterang commentedon May 27, 2019
let moveZero = (arr) => {
let point = 0
for (var i = 0; i < arr.length; i++) {
if (arr[i]!=0) {
arr[point] = arr[i]
arr[i] = 0
point++
}
}
return arr
}
tanggd commentedon May 27, 2019
最优解法
想到好几个方法,楼上都写出来了,但是我觉得这些都不是最优解法,既然是算法题,自然是以算法的思维去解。
y1324 commentedon May 27, 2019
那个这个问题怎么解决?没头绪
wheatma commentedon May 27, 2019
moorain commentedon May 27, 2019
y1324 commentedon May 27, 2019
为什么倒序可以解决这个办法
moorain commentedon May 27, 2019
因为待处理的数据索引没有变。https://www.jianshu.com/p/77247e9e1849
225 remaining items
qifengla commentedon May 31, 2023
shizhouyu commentedon May 31, 2023
Stephen-Monster commentedon May 31, 2023
88wixi commentedon Jul 24, 2023
let arr = [0, 1, 0, 3, 12, 0, 9, 8, 6, 0, 1]
function changeArea(arr) {
arr.forEach((element, index) => {
if (element === 0) {
for (i = index; i < arr.length - 1; i++) {
let temp
temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
}
}
});
}
changeArea(arr)
console.log(arr)
shizhouyu commentedon Jul 24, 2023
Stephen-Monster commentedon Jul 24, 2023
wut1 commentedon Aug 12, 2023
let len = nums.length
let i = 0
let max = len
while(i < max){
if(nums[i] === 0){
nums.splice(i,1)
nums.push(0)
max--
} else {
i++
}
}
return nums
shizhouyu commentedon Aug 12, 2023
Stephen-Monster commentedon Aug 12, 2023
shizhouyu commentedon Nov 3, 2023
Stephen-Monster commentedon Nov 3, 2023
xiguahuibaozha commentedon Nov 3, 2023
[0, 1, 0, 3, 12, 0, 9, 8, 6, 0, 1].sort((a,b) => { if(b){ return 0 }else { return -1 } })
MyPrototypeWhat commentedon Jun 3, 2024
一个循环就结束 很简单
shizhouyu commentedon Jun 3, 2024
Stephen-Monster commentedon Jun 3, 2024