题目

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]

代码思路

标准是不允许创建新的array,且仅在原arr上改动。一般情况下,我们需要数有多少个0,然后就会有多少个末尾数字被丢弃, 然后倒序赋值,遇到0赋值两次。

  1. if(value == 0): dups += 1

但是仅仅这样子是不行的,

我们还需要考虑一些特殊情况。
[1,2,3,0,0,0,4], 这种情况下,最后一个0是会被丢弃而不是重复的,所以我们数0的时候要增加条件限制,
即 if(i > length_ - dups),则此时超出了arr的范围,应跳出循环。

那么同理 if(i == length_ - dups), 此时的0可以被放入,但是因为arr正好满了,因此不能被重复,也应作为特殊情况考虑。

if(i < length_ - dups), 此时为一般情况,用正常逻辑即可。

综上所述,答案可为下面代码

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        dups = 0
        length_ = len(arr) - 1
        for i, value in enumerate (arr):
            if(i > length_ - dups):
                break
            if(value == 0):

                if(i < length_ - dups):
                    dups += 1
                # edge case: if the last stored digit is 0, it doesn't need to be dup
                elif(i == length_ - dups):
                    arr[length_] = 0
                    length_ -= 1
                else:
                    break

        for i in range(length_ - dups, -1, -1):      
            if(arr[i] == 0):
                arr[i+dups] = 0
                dups -= 1
                arr[i+dups] = 0
            else:
                arr[i+dups] = arr[i]