leetcode-1089-easy

发布时间 2023-03-29 20:44:48作者: iyiluo

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

思路一:遍历数组,统计扩展后的长度,生成扩展后的数组,然后把值复制到原来的数组上。刚开始想实现在原来数组上修改,写出来发现总有 bug,越来越复杂,最后直接用最简单的方案

    public void duplicateZeros(int[] arr) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 0) {
                count += 2;
            } else {
                count++;
            }
        }

        int[] clone = new int[count];
        int idx = 0;
        for (int num : arr) {
            if (num == 0) {
                idx += 2;
            } else {
                clone[idx++] = num;
            }
        }

        System.arraycopy(clone, 0, arr, 0, arr.length);
    }

思路二:先算出一个 end index,从数组后面往前赋值