一.问题描述
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 <= 100000 <= arr[i] <= 9
二.解决思路
这道题有两种方法解决,一种是用空间换时间,新开一个数组,然后一个一个往里面加元素,碰到0就加两个0进去。
时间复杂度为O(N)
第二种方法是时间换空间,碰到0就加两个0到当前数组,然后后面的元素一个个向后移,有点像冒泡排序。
时间复杂度为O(N*N)
这道题要注意的是当用第一张方法的时候,记得要直接改变arr指向的值,而不是改变它引用本身,因为leetcode判定程序还是记录着一开始的引用值,可以去了解一下leetcode的变量引用机制。
给出两种实现方法。
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
1.新开数组
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
len_arr=len(arr)
rst=[]
for num in arr:
if num==0:
rst.append(0)
rst.append(0)
else:rst.append(num)
if len(rst)>=len_arr:
arr[:]=rst[:len_arr]
# arr=rst[:len_arr] this do not work
break
2.往后移动
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i=0
while i<len(arr):
if arr[i]==0:
arr.pop() # O(1)
arr.insert(i+1,0) # O(N)
i+=2
else:i+=1
本文探讨了在固定长度数组中遇到零时如何将其复制并保持其他元素不变的问题,提供了两种解决方案:一是使用额外空间进行元素复制,二是通过时间换空间的方式在原数组上操作。详细介绍了每种方法的实现过程及时间复杂度。
531

被折叠的 条评论
为什么被折叠?



