1089. Duplicate Zeros - Easy

本文介绍了一种算法,用于在一个固定长度的整数数组中,将每个零的出现复制一次,并将剩余元素向右移动。该操作在原数组上进行,不返回任何值。文章提供了具体实现代码,采用O(n)的时间复杂度和O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a fixed length array arr of integers, 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, do not return anything from your function.

 

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

 

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

Hint: Iterate through the array backwards. You know whether an integer should be written or not based on how many zeroes are remaining in the array.

 

注意在第二次iterate覆盖赋值的时候,超出原数组长度的部分不用管,只在原数组长度范围内写入新值就行

time: O(n), space: O(1)

class Solution {
    public void duplicateZeros(int[] arr) {
        int cnt = 0;    // count zeros
        for(int n : arr) {
            if(n == 0) {
                cnt++;
            }
        }
        
        int n = arr.length + cnt;
        int i = n - 1, j = arr.length - 1;
        while(i >= 0 && j >= 0) {
            if(arr[j] == 0) {
                if(i < arr.length) {
                    arr[i] = 0;
                }
                i--;
                if(i < arr.length) {
                    arr[i] = 0;
                }
            } else {
                if(i < arr.length) {
                    arr[i] = arr[j];
                }
            }
            i--;
            j--;
        }
    }
}

 

转载于:https://www.cnblogs.com/fatttcat/p/11330452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值