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--;
    }
}
相关推荐
老歌老听老掉牙3 小时前
两个平面旋转平移坐标系间的坐标变换关系
python·算法·平面·旋转·平移
W.A委员会3 小时前
PID与PID整定
python·算法
冷雨夜中漫步3 小时前
YOLO快速入门——(2)YOLO V26安装与快速入门
图像处理·算法·yolo·计算机视觉
longlongzihan3 小时前
LeetCode 41. 缺失的第一个正数:从基础解法到原地哈希
c++·算法·leetcode
Omics Pro3 小时前
强生:以机理为中心!虚拟细胞世界模型
数据库·人工智能·python·深度学习·算法·机器学习·自然语言处理
FPGA信号处理4 小时前
【凸优化】第一节课(下):保凸运算、分离超平面与 Farkas 引理
人工智能·算法·机器学习
怕浪猫4 小时前
Agent 的记忆系统怎么设计?面试官想听的是这个
算法·面试·github
C++ 老炮儿的技术栈4 小时前
C++ const 的3个核心作用
服务器·c语言·c++·算法·c
有毒的教程4 小时前
Dev-C++ 避免爆栈(Stack Overflow)完整方案
c++·算法·深度优先
在所不辞兄4 小时前
刚性问题误差容限设置技巧
深度学习·神经网络·算法·机器学习