题目描述
自己解法
对于就地
算法的理解不够,就地修改要求空间复杂度为
O
(
1
)
O(1)
O(1)。自己的解法虽然时间性能较好,但空间复杂度为
O
(
n
)
O(n)
O(n),不符合题目要求,Python代码:
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
old = arr[:]
temp = 0
zero_count = [0] * len(arr)
for i in range(len(arr)):
if arr[i] == 0:
temp += 1
arr[i] = 0
zero_count[i] = temp
for i in range(len(arr)):
if i+zero_count[i] >= len(arr):
break
if zero_count[i] > 0:
arr[i+zero_count[i]] = old[i]
else:
arr[i] = old[i]
官方解答
官方解答的思路是计算由于复制0导致原数组丢失元素的个数,找到最终数组的最后一个元素,然后倒序遍历,具体参考:官方解答。
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
possible_dups = 0
length_ = len(arr) - 1
# Find the number of zeros to be duplicated
for left in range(length_ + 1):
# Stop when left points beyond the last element in the original list
# which would be part of the modified list
if left > length_ - possible_dups:
break
# Count the zeros
if arr[left] == 0:
# Edge case: This zero can't be duplicated. We have no more space,
# as left is pointing to the last element which could be included
if left == length_ - possible_dups:
arr[length_] = 0 # For this zero we just copy it without duplication.
length_ -= 1
break
possible_dups += 1
# Start backwards from the last element which would be part of new list.
last = length_ - possible_dups
# Copy zero twice, and non zero once.
for i in range(last, -1, -1):
if arr[i] == 0:
arr[i + possible_dups] = 0
possible_dups -= 1
arr[i + possible_dups] = 0
else:
arr[i + possible_dups] = arr[i]