Move Zeroes

박정현·2022년 3월 18일
0

LeetCode

목록 보기
14/18
post-thumbnail

문제

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

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:

Input: nums = [0]
Output: [0]

Constraints:

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

첫번째 시도

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

❗️ 반복문을 돌면서 0이 나오면 splice와 push로 0을 해당 자리에서 빼서 뒤에 붙이도록 코드를 짜고
i--로 다시 그 자리부터 검색하려 했으나 처음 요소가 0인 경우 인덱스 -1부터 검색을 하면서 Timeout으로 처리가 됐다😹

풀이

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

✅ 이것저것 시도해보다가 반복문을 뒤에서부터 돌리면 첫번째 시도에서 겪은 문제는 해결이 될 것 같았다.
문제는 풀었지만 아직 아리까리 해서 조금 더 디버깅을 해봐야할듯!

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글