美文网首页
LeetCode 1089. Duplicate Zeros (

LeetCode 1089. Duplicate Zeros (

作者: LiNGYu_NiverSe | 来源:发表于2020-11-13 00:54 被阅读0次

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:

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        i = 0
        n = len(arr)

        while i < n:
            if arr[i] == 0:
                arr.pop()
                arr.insert(i,0)
                i += 1
            i += 1

Explanation:
We scan the arr from left to right, if the i-th element is equal to 0, we pop the last arr to make a position for replicating a new 0. Just keep in mind that i has to be less than n, because we don't need to do anything for the last element even though it is 0. Otherwise, we will see an index error(out of range), because we need to delete the last element and original index is gone.

相关文章

网友评论

      本文标题:LeetCode 1089. Duplicate Zeros (

      本文链接:https://www.haomeiwen.com/subject/algmbktx.html