[LeetCode] Duplicate Zeros

준규·2022년 12월 16일

1.문제


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.


숫자 배열 arr가 주어질 때 숫자가 0이라면 그 뒤에 0을 하나 더 추가한 배열을 리턴하는 문제이다. 이때 원래 배열의 길이를 넘는 숫자들은 arr에 포함되지 않는다.


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

2.풀이

  1. 배열을 순회하면서 0이라면 바로뒤에 0을 추가한다.
  2. 순회하면서 0이 나온 횟수를 count에 저장한다.
  3. 마지막에 arr배열의 끝에서 count 만큼을 잘라준다.

/**
 * @param {number[]} arr
 * @return {void} Do not return anything, modify arr in-place instead.
 */
var duplicateZeros = function(arr) {
    let count = 0;
    let length = arr.length
    for(let i = 0 ; i < arr.length; i ++) {
        if(arr[i] === 0) {
            arr.splice(i,0,0);
            i++;
            count++
        }
    }

    arr.splice(length, count);
    
};

3.결과

profile
안녕하세요 :)

0개의 댓글