描述
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 就按算法操作,如果不是 0 就继续往下遍历。时间复杂度为 O(N),空间复杂度为 O(1)因为没有用到新的空间,直接在原地址上修改数据。
解答
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
if arr:
N = len(arr)
i = 0
while i < N:
if arr[i] != 0:
i+=1
continue
else:
arr.insert(i,0)
arr.pop(-1)
i = i+2
运行结果
Runtime: 52 ms, faster than 88.42% of Python online submissions for Duplicate Zeros.
Memory Usage: 11.9 MB, less than 100.00% of Python online submissions for Duplicate Zeros.
每日格言:每个人都有属于自己的一片森林,迷失的人迷失了,相逢的人会再相逢。
感谢支持 支付宝