관리 메뉴

bright jazz music

283. Move Zeroes 본문

Algorithm Practice/LeetCode

283. Move Zeroes

bright jazz music 2026. 1. 21. 22:21
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
 

Follow up: Could you minimize the total number of operations done?
/**
 Do not return anything, modify nums in-place instead.
 */
 
// 접근 방법
//Two Pointer 방식을 사용
// left 포인터: 0이 아닌 요소를 배치할 위치
// right 포인터: 배열을 순회하면서 0이 아닌 요소를 찾음

function moveZeroes(nums: number[]): void {
   let left = 0;

   for(let right = 0; right < nums.length; right++) {
        if(nums[right] !== 0) {
            if(left !== right) {
                [nums[left], nums[right]] = [nums[right], nums[left]]
            }
            // left는 "0이 아닌 요소가 들어갈 위치"를 가리킨다.
            // right는 배열을 순회하면서 계속 증가한다.
            // right가 0이 아닌 값을 만나면:
            //   1. left와 right의 위치를 바꾼다 (만약 다르다면)
            //   2. left를 증가시킨다 (다음 0이 아닌 값이 들어갈 자리로 이동)
            left++;
        }
   }

//    return nums
};



/* 아래와 같이 하는 게 풀어쓴 방식
var moveZeroes = function(nums) {
    let left = 0; // 0이 아닌 요소를 배치할 위치
    
    // 1단계: 0이 아닌 요소들을 앞으로 이동
    for (let right = 0; right < nums.length; right++) {
        if (nums[right] !== 0) {
            nums[left] = nums[right];
            left++;
        }
    }
    
    // 2단계: 남은 위치를 0으로 채우기
    for (let i = left; i < nums.length; i++) {
        nums[i] = 0;
    }
};

*/

'Algorithm Practice > LeetCode' 카테고리의 다른 글

443. String Compression  (0) 2026.01.19
334. Increasing Triplet Subsequence  (0) 2026.01.17
238. Product of Array Except Self  (0) 2026.01.16
151. Reverse Words in a String  (0) 2026.01.15
345. Reverse Vowels of a String  (0) 2026.01.14
Comments