[Array101] Q. Duplicate Zeros

myminimin·2023년 7월 30일
0

page

Duplicate Zeros

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Example 1:

	Input: arr = [1,0,2,3,0,4,5,0]
	Output: [1,0,0,2,3,0,0,4]
	Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

	Input: arr = [1,2,3]
	Output: [1,2,3]
	Explanation: After calling your function, the input array is modified to: [1,2,3]
  • Constraints:
    1 <= arr.length <= 104
    0 <= arr[i] <= 9

answer

    class Solution {
    public void duplicateZeros(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];
        int j = 0;

        for (int i = 0; i < n && j < n; i++) {
            if (arr[i] == 0 && j < n - 1) {
                temp[j++] = 0;
                temp[j++] = 0;
            } else {
                temp[j++] = arr[i];
            }
        }

        System.arraycopy(temp, 0, arr, 0, n);
    }
}

변수 n에 배열 arr의 길이를 저장하고 temp라는 새로운 정수 배열의 크기를 n과 동일하게 설정한다. (temp는 이따가 결과를 저장하는 용도로 사용함)
j는 temp 배열의 인덱스를 나타내는 변수.

반복문에서 배열 arr를 탐색하는데 0부터 시작, i가 n보다 작으면서 j가 n보다 작을 동안에만 반복한다.
만약 arr[i]가 0이고 j가 n-1보다 작으면, 즉 현재 요소가 0이고 뒤에 공간이 남아있는 상태일 때 0을 두 번 복사한다!

temp[j++] = 0 ; temp[j]에 0을 대입하고, j를 1증가. 다음 인덱스인 temp[j]에 또 0을 대입하고 j를 다시 1 증가시키면 0이 두 번 복사되어 temp 배열에 저장이 된다.

만약 arr[i]가 0이 아니거나 더 이상 뒤에 공간이 없는 경우에는 해당 값을 temp[j]에 저장한다.

else의 경우에는 temp[j]에 arr[i]값을 대입하고 j를 1 증가시킨다. 이렇게 되면 arr[i]가 0이 아니면 그 값을 그대로 temp 배열에 저장한다!

반복문이 다 끝나면 배열 temp에는 0이 복사된 상태인데 이때 System.arraycopy를 이용해서 temp 배열의 내용을 arr 배열로 복사!

이러면 문제가 원했던 0이 있을 경우 0을 복제하는 게 가능하다!

1개의 댓글

comment-user-thumbnail
2023년 7월 31일

좋은 글 감사합니다.

답글 달기