interger를 포함한 배열 nums이 주어졌을 때, 나머지 원소의 상대적 순서를 유지하면서 모든 0을 배열의 끝으로 보내시오.
Note 복사본을 만들지 않고 이 배열안에서 자체적으로 해결해야 합니다
Ex 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Ex 2:
Input: nums = [0]
Output: [0]
아래의 코드
var moveZeroes = function(nums) {
nums.forEach((element,index)=>{
if(element===0){
nums.splice(index,1)
nums.push(0)
}
})
};
[0,0,3] 이라는 nums를 예로들자면, index 0에있는 첫 0은 제대로 끝으로 옮겨지지만 첫 0이 사라지는 바람에 두 번째 0이 첫 index로 옮겨지게 되고, forEach는 그 다음인 index 1로 옮겨진 3부터 다음 반복을 시작했습니다.
즉 forEach가 두 번째 0은 스킵하는 문제였습니다.
var moveZeroes = function(nums) {
for(i = nums.length; i>=0; i--)
if(nums[i]===0){
nums.splice(i,1);
nums.push(0)
}
};
var moveZeroes = function(nums) {
for(i = nums.length; i>=0; i--)
if(nums[i]===0){
nums.splice(i,1);
nums.push(0)
}
};
위의 코드를 논리 연산자 &&을 사용해서 더 간략하게 줄일 수 있습니다.
var moveZeroes = function(nums) {
for(i = nums.length; i >= 0; i--) {
nums[i]===0 && nums.splice(i, 1) && nums.push(0)
}