[LeetCode] Move Zeroes (JS)

nRecode·2020년 9월 15일
0

Algorithm

목록 보기
10/48

문제

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

입출력 예

Example 1

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

접근

  1. 배열을 for문으로 접근하여서 0 발견시 splice
  2. push(0)

풀이

var moveZeroes = function(nums) {
    for(let i = nums.length - 1; i >= 0; i--){
        if(!nums[i]){
            nums.splice(i,1);
            nums.push(0);
        }
    }
    return nums;
};

위와 같이 풀이하고 배열도 copy하였지만 음,,, 맞는 방법인지는 모르겠다 ㅜ

profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글