LeetCode - 1089. Duplicate Zeros(array, two pointers)

YAMAMAMO·2022년 1월 24일
0

LeetCode

목록 보기
4/100

문제

https://leetcode.com/problems/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.

고정 길이 정수 배열이 주어지면 0이 나올 때마다 중복하여 나머지 요소를 오른쪽으로 이동합니다.
원래 배열의 길이를 초과하는 요소는 기록되지 않습니다. 입력 배열에 대해 위의 내용을 수정한 후 아무 것도 반환하지 마십시오.

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]

분류

array, two pointers

풀이

자바입니다.
1.배열을 순서대로 반복한다.
2.0을 찾는다.
3.배열의 마지막에서부터 오른쪽으로 쉬프트한다. i+1번째에서 멈춘다.
4.i++한다.(중요)

class Solution {
    public void duplicateZeros(int[] arr) {
        for(int i=0;i<arr.length;i++){
            if(arr[i]==0){
                for(int j=arr.length-1;j>i;j--){
                    arr[j]=arr[j-1]; 
                }
                i++;
            }
        }
    }
}
profile
안드로이드 개발자

0개의 댓글