1089. Duplicate Zeros - Easy

Given a fixed length array arr of integers, 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, do not return anything from your function.

 

Example 1:

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

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

 

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

Hint: Iterate through the array backwards. You know whether an integer should be written or not based on how many zeroes are remaining in the array.

 

Note that at the time of second iterate cover assignment, beyond the original length of the array is not part of the tube, only the new value is written in the original length of the array on the line

time: O (n) space: O (1)

class Solution {
    public void duplicateZeros(int[] arr) {
        int cnt = 0;    // count zeros
        for(int n : arr) {
            if(n == 0) {
                cnt++;
            }
        }
        
        int n = arr.length + cnt;
        int i = n - 1, j = arr.length - 1;
        while(i >= 0 && j >= 0) {
            if(arr[j] == 0) {
                if(i < arr.length) {
                    arr[i] = 0;
                }
                i--;
                if(i < arr.length) {
                    arr[i] = 0;
                }
            } else {
                if(i < arr.length) {
                    arr[i] = arr[j];
                }
            }
            i--;
            j--;
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/fatttcat/p/11330452.html