LeetCode 코딩 문제 2020/12/13 - Move Zeroes

이호현·2020년 12월 13일
0

Algorithm

목록 보기
31/138

[문제]

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.

(요약) 0을 제일 뒤로 다 몰아넣어라.

[풀이]

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

배열 마지막 요소부터 순회하면서 0이면 잘라서 배열 마지막으로 보냄.

profile
평생 개발자로 살고싶습니다

0개의 댓글