[leetcode] 1089. Duplicate Zeros

Description

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.

分析

题目的意思是:给定一个数组,如果有0就要变成两个0,变完了之后还是保留数组长度不变,意味着数组变长了的话,多了的部分就要省去,我这里先算出最后加入0后的长度,从后往前遍历复制原来数组上的值到新的位置,如果该位置超出了原来的位置了就舍弃就行了。

代码

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        cnt=0
        for item in arr:
            if(item==0):
                cnt+=1
        n1=len(arr)
        n=len(arr)+cnt
        j=n-1
        for i in range(n1-1,-1,-1):
            if(arr[i]==0):
                if(j<=n1-1):
                    arr[j]=0
                j-=1
                if(j<=n1-1):
                    arr[j]=0
                j-=1
            else:
                if(j<=n1-1):
                    arr[j]=arr[i]
                j-=1
        return None
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值