#1089 Duplicate Zeros
Given a fixed-length integer array
arr, 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 and do not return anything.
解题思路:
for循环找0。找到后把此时idx往后的信息存在temp里。然后在改idx+1后的信息。设置skip= True跳过下一个0。
跳过0后把跳过指令改为false(初始是False)。
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
idx = 0
skip = False
for i in arr:
if not skip:
if not i: # i = 0
temp = arr[idx:len(arr)-1]
arr[idx+1:len(arr)] = temp
skip = True
else:
skip = False
idx += 1
Runtime:

emmm,看一下52ms solution:

可以直接用insert改变所有0后面的信息,然后用pop 去掉最后一个。然后在if block判断是否为零里加idx += 1来跳过下个被复制的零。
重写了一下:
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
idx = 0
n = len(arr) - 1
while idx<n:
if not arr[idx]: # i = 0
arr.insert(idx+1, 0)
arr.pop()
idx += 1
idx += 1
runtime:

#88 Merge Sorted Array
You are given two integer arrays
nums1andnums2, sorted in non-decreasing order, and two integersmandn, representing the number of elements innums1andnums2respectively.Merge
nums1andnums2into a single array sorted in non-decreasing order.The final sorted array should not be returned by the function, but instead be stored inside the array
nums1. To accommodate this,nums1has a length ofm + n, where the firstmelements denote the elements that should be merged, and the lastnelements are set to0and should be ignored.nums2has a length ofn.
解题思路:
nums1保留[:m],接上nums2 取代nums1.然后再sorted。
但是却不行🚫。
好奇怪。后来看解答说是,这样time complexity太大,sorted(x)的话是O(xlogx)。(但也不应该是🚫?PyCharm跑的话是没问题能跑出来。回头研究一下为啥)
但是直接改掉nums1[m:] = nums2[:n],再sorted就行。runtime还有85%。
然后推荐了一种三指针的方法。两个读数指针分别在nums1(非零的)和nums2的尾部,还有一个写数指针在nums1的尾部。等于是从尾往头往nums1塞值。比较两读数指针的数值大小,大的写入。
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
p, p1, p2 = m+n-1, m-1, n-1
while p2 >= 0:
if p1 >= 0 and nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
p -= 1
runtime:

20ms的solution也是这种solution。
大家提醒,虽然这题是easy,但是要学会用medium的思路解题。不满足于做出来。尽量多种解题思路。
本文探讨了两个编程挑战的解决方案,一个是数组中的零复制问题,另一个是有序数组合并。针对零复制问题,提出了两种不同的Python实现,分别使用了for循环和插入操作。而在有序数组合并中,对比了直接修改数组与使用排序的效率,并推荐了使用三指针的方法。强调在解题时不仅要追求正确性,还要考虑时间复杂度和解题多样性。

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



