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--;
    }
}
相关推荐
2501_914245931 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Jerry2 小时前
LeetCode 101. 对称二叉树
算法
可编程芯片开发3 小时前
基于MPPT最大功率跟踪的离网光伏发电系统Simulink建模与仿真
算法
AI科技星3 小时前
线性算子不是空间映射函数,是全域双螺旋场之间拉伸、旋转、耦合、坍缩的跨空间标准化变换载体《全域数学vs传统数学:人类文明进阶200讲》第80讲
线性代数·算法·矩阵·数据挖掘·回归·乖乖数学·全域数学
米罗篮3 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
2501_914245933 小时前
C语言与硬件交互:从GPIO到中断的嵌入式编程实践
c语言·单片机·交互
dream_home84073 小时前
图像算法模型NPU适配与算法服务实战指南
人工智能·python·算法·npu 图像服务
大鱼>4 小时前
多宠物家庭智能管理平台:云端架构与多设备协同实战
python·算法·iot·宠物
炸膛坦客5 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
To_OC5 小时前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode