#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
nums1
andnums2
, sorted in non-decreasing order, and two integersm
andn
, representing the number of elements innums1
andnums2
respectively.Merge
nums1
andnums2
into 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,nums1
has a length ofm + n
, where the firstm
elements denote the elements that should be merged, and the lastn
elements are set to0
and should be ignored.nums2
has 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的思路解题。不满足于做出来。尽量多种解题思路。