LeetCode //C - 1089. Duplicate Zeros

1089. 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 < = a r r . l e n g t h < = 10 4 1 <= arr.length <= 10^4 1<=arr.length<=104
  • 0 <= arri <= 9

From: LeetCode

Link: 1089. Duplicate Zeros


Solution:

Ideas:
  • Treat the array as if it had extra space (arrSize + zeros)
  • Only write values when index < arrSize
  • Backward processing avoids overwriting unprocessed elements
Code:
c 复制代码
void duplicateZeros(int* arr, int arrSize) {
    int zeros = 0;

    for (int i = 0; i < arrSize; i++) {
        if (arr[i] == 0) {
            zeros++;
        }
    }

    int i = arrSize - 1;
    int j = arrSize + zeros - 1;

    while (i >= 0) {
        if (j < arrSize) {
            arr[j] = arr[i];
        }

        if (arr[i] == 0) {
            j--;
            if (j >= 0 && j < arrSize) {
                arr[j] = 0;
            }
        }

        i--;
        j--;
    }
}
相关推荐
用户9385156350724 分钟前
从 O(n²) 到 O(nlogn):一文读懂快速排序的“快”与“妙”
javascript·算法
To_OC1 小时前
手写快排次次翻车?别死背快排模板了,这才是面试官想听的底层逻辑
javascript·算法·排序算法
饼干哥哥2 小时前
Reddit VOC调研太慢?搭一个AI专家团队半小时洞察任何品类|以猫用饮水机为例
人工智能·算法·ai编程
地平线开发者3 小时前
Transformer模型部署之性能优化指南
算法
地平线开发者4 小时前
人在途中:从“编译失败”到“模型可落地”——CUDA 自定义算子
算法·自动驾驶
半个落月7 小时前
从递归到快速排序:用 JavaScript 把分治思想讲明白
javascript·算法·面试
小月土星7 小时前
JavaScript 快速排序:从 pivot、双指针到分治思想
javascript·算法·面试
小月土星8 小时前
JavaScript 递归入门:从 1 到 n 求和,再到数组扁平化
javascript·算法·面试
To_OC1 天前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode