1089. Duplicate Zeros
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.
这个要求inplace,不能用额外的数组辅助。
先计算出变换后数组的长度,然后从后往前更新数组,超出长度的就不更新。遇到0就写两个
class Solution(object): def duplicateZeros(self, arr): """ :type arr: List[int] :rtype: None Do not return anything, modify arr in-place instead. """ zero_num = 0 n = len(arr) for value in arr: if value == 0: zero_num += 1 num = n + zero_num - 1 for i in range(n - 1, -1, -1): if arr[i] != 0: if num < n: arr[num]= arr[i] num -= 1 else: if num < n: arr[num] = arr[i] num -= 1 if num < n: arr[num] = arr[i] num -= 1 return None