Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
const moveZeroes = nums => {
for(let i=0;i<nums.length;i++){
if(Math.abs(nums[i]) == 0){
nums.splice(i,1);
nums.push(0);
}
}
return nums;
}
0이 앞에 연속으로 있으면 인덱스의 0번째가 바뀌기 때문에 slice()를 사용해도 걸러지지 않는 부분이 있었다.
slice()를 사용하고싶다면 배열을 앞이 아닌 뒤에서부터 돌렸어야 한다.
const moveZeroes = nums => {
let count = 0;
for(let i =0;i<nums.length;i++){
if(nums[i] ===0){
count++;
}
}
const a = nums.filter(n =>{ return n!=0});
for(let i =0;i<count;i++){
a.push(0);
}
return a;
}