[LeetCode / Easy] 283. Move Zeroes (Java)

이하얀·2025년 3월 9일
0

📙 LeetCode

목록 보기
12/13

💬 Info



Problem

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]

예시 2

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

Constraints

  • 1 <= nums.length <= 10410^4
  • 231-2^{31} <= nums[i] <= 2312^{31} - 1


문제 이해

  • 배열 순서를 유지하면서 0을 배열 끝으로 이동시키기


알고리즘

풀이 시간 : 5분

  • 0이 아닌 숫자를 앞에서부터 차례로 저장
  • 남은 부분 : 0으로 채우기
class Solution {
    public void moveZeroes(int[] nums) {
        int index = 0;
        
        for (int num : nums) {
            if (num != 0) {
                nums[index++] = num;
            }
        }
        
        while (index < nums.length) {
            nums[index++] = 0;
        }
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글