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 <= arr.length <= 10000
  • 0 <= arr[i] <= 9

Solution in python:

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        index = -1
        i = 0
        flag = False
        while index < len(arr):
            if index == len(arr)-1:
                break
            if arr[i] != 0:
                index += 1
            elif arr[i] == 0 and index + 2 < len(arr):
                index += 2
            else:
                flag = True
                index += 1
            i += 1
        j = i-1
        i = len(arr)-1
        while i >= 0:
            if arr[j] != 0:
                arr[i] = arr[j]
                j -= 1
                i -= 1
            elif arr[j] == 0 and flag and i == len(arr)-1:
                arr[i] = 0
                j -= 1
                i -= 1
            else:
                arr[i] = 0
                arr[i-1] = 0
                j -= 1
                i -= 2

        return arr
最后修改日期: 2021年3月4日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。