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--;
    }
}
相关推荐
AndrewHZ5 小时前
【LLM技术全景】阶段总结:技术原理篇核心知识回顾
人工智能·深度学习·算法·语言模型·大模型·llm·芯片开发
小星星闪亮登场6 小时前
2026萌新联赛第三场-- (郑州轻工业大学)
数据结构·c++·经验分享·算法·贪心算法·排序算法·深度优先
冻柠檬飞冰走茶6 小时前
PTA基础编程题目集 7-8超速判断(C++语言实现)
开发语言·数据结构·c++·算法
玖玥拾7 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
数据皮皮侠AI7 小时前
上市公司数字供应链金融指数(2010-2024)
大数据·人工智能·算法
stevenseahang7 小时前
C语言标准演化史:从K&R到GNU,谁才是正统?
c语言·gnu·可移植性·标准演化·ansic
小程故事多_807 小时前
用GRPO算法重塑多智能体系统,从原理落地到复杂任务规划实战
人工智能·算法
别动我齐刘海8 小时前
Day6 unitree_G1人形机器人GMR—— MotionInput
c语言·c++·人工智能·学习·机器学习·机器人·github
Hi李耶8 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
shylyly_8 小时前
104.二叉树的最大深度
数据结构·算法·104.二叉树的最大深度