[E] 283. Move Zeroes

YJ·2025년 3월 27일

leetcode

목록 보기
18/100

https://leetcode.com/problems/move-zeroes

문제

배열 주어지면 순서를 유지한 채 0만 맨 뒤로 옮기기
(조건: 다른 배열을 만들면 안 됨)

답안

public void moveZeroes(int[] nums) {
	int j = 0;
	int zeroCount = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 0) {
			zeroCount++;
			continue;
		}
		nums[j++] = nums[i];
	}
	int len = nums.length;
	for (int i = 1; i <= zeroCount; i++) {
		nums[len - i] = 0;
	}
}

two pointer 로 0이 아니면 맞는 자리에 해당 숫자 넣어주고, 0 이면 따로 count 해서 뒤에서부터 채워주기

메모

나는 0을 따로 세어줬는데, j index 랑 배열 length 를 비교해서 while 로 작으면 계속 0을 채워주는 방식이 더 간결하고 깔끔하다.

profile
Hello

0개의 댓글