88. 归并有序数组(easy)
题目
V1
从nums1的末尾开始,倒序比较两个数组值的大小。
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if m == 0:
nums1[:] = nums2 # [:]不要漏,否则跳出函数后nums1的值并未改变
return
if n == 0:
return
i, j = m - 1, n - 1
for t in range(len(nums1))[::-1]:
if j == -1:
nums1[t] = nums1[i]
i -= 1
continue
elif i == -1:
nums1[t] = nums2[j]
j -= 1
continue
if nums1[i] > nums2[j]:
nums1[t] = nums1[i]
i -= 1
elif nums1[i] <= nums2[j]:
nums1[t] = nums2[j]
j -= 1
结果:
V2
V1 中开头m == 0 和 m== 0的条件不需要了,删掉
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i, j = m - 1, n - 1
for t in range(len(nums1))[::-1]:
if j == -1:
nums1[t] = nums1[i]
i -= 1
elif i == -1:
nums1[t] = nums2[j]
j -= 1
elif nums1[i] > nums2[j]:
nums1[t] = nums1[i]
i -= 1
elif nums1[i] <= nums2[j]:
nums1[t] = nums2[j]
j -= 1
结果:
524. 最长的子序列(medium)
题目
V1暴力解法
直接在 dictionary 中依次与 s 进行对比。
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
out = ""
for str in dictionary:
i, j = 0, 0
while i < len(str) and j < len(s):
if str[i] == s[j]:
i += 1
j += 1
if i == len(str):
if len(str) > len(out):
out = str
elif len(str) == len(out):
if str < out:
out = str
return out
结果:
V2
在V1上修改了一点点,速度有所提升。
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
out = ""
for str in dictionary:
i, j = 0, 0
for j in range(len(s)):
if i < len(str) and str[i] == s[j]:
i += 1
if i == len(str):
if len(str) > len(out):
out = str
elif len(str) == len(out):
if str < out:
out = str
return out
结果:
但是我不明白为什么只是把 while 循环改成 for 循环后运行速度就快了一截?,此处存疑。