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--;
    }
}
相关推荐
dear_bi_MyOnly1 分钟前
C语言控制语句与循环逻辑精讲
c语言·开发语言·学习·分类
学linux的QQ蛋11 分钟前
Linux 文件 IO:系统调用 open/read/write 完整总结
linux·运维·算法
rannn_11116 分钟前
【力扣hot100】回溯专题|全排列、子集、字母组合、组合总和、括号生成、单词搜索、分割回文串、N皇后
java·算法·leetcode·回溯
旖旎夜光30 分钟前
LCR 173:在点名(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找
重生之后端学习32 分钟前
438. 找到字符串中所有字母异位词[中等]✅
开发语言·数据结构·算法·leetcode·职场和发展
渡之34 分钟前
ArduPilot LowPassFilter 深度解析
算法·无人机
ting94520009 小时前
Humalike X Hermes 深度技术剖析:单指令注入群聊社交智能的底层架构、算法与跨 IM 平台实现
人工智能·算法·架构
吴声子夜歌9 小时前
Java面试——算法
java·算法·面试
evans在进步9 小时前
LeetCode 64:最小路径和——Java 原地动态规划详解
java·leetcode·动态规划
h_a_o777oah9 小时前
【图论】Tarjan 缩点:解决有向图中环的问题
c++·算法·图论·acm·强连通分量·缩点·tarjan