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 <= arr.length <= 10000.
- 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