【发布时间】:2021-02-25 02:59:27
【问题描述】:
所以昨晚我解决了this LeetCode question。我的解决方案不是很好,很慢。所以我试图计算我的算法的复杂度,以与 LeetCode 在解决方案部分中列出的标准算法进行比较。这是我的解决方案:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# Get lengths of all strings in the list and get the minimum
# since common prefix can't be longer than the shortest string.
# Catch ValueError if list is empty
try:
min_len = min(len(i) for i in strs)
except ValueError:
return ''
# split strings into sets character-wise
foo = [set(list(zip(*strs))[k]) for k in range(min_len)]
# Now go through the resulting list and check whether resulting sets have length of 1
# If true then add those characters to the prefix list. Break as soon as encounter
# a set of length > 1.
prefix = []
for i in foo:
if len(i) == 1:
x, = i
prefix.append(x)
else:
break
common_prefix = ''.join(prefix)
return common_prefix
我在计算复杂性方面有点吃力。第一步 - 获取字符串的最小长度 - 需要 O(n) ,其中 n 是列表中的字符串数。然后最后一步也很简单——它应该花费 O(m),其中 m 是最短字符串的长度。
但中间的部分令人困惑。 set(list(zip(*strs))) 应该希望再次采用 O(m),然后我们这样做 n 次,所以 O(mn)。但是总体复杂度为 O(mn + m + n),这对于解决方案的速度来说似乎太低了。
另一种选择是中间步骤是O(m^2*n),这更有意义。这里计算复杂度的正确方法是什么?
【问题讨论】:
-
旁注:我发现 leetcode 报告的运行时可能受到外部因素的影响。因此,如果您的结果看起来很糟糕,请不要紧张,因为它可能只是一个缓慢的服务器。
-
另一件事是扫描许多字符串的第 ??th 个字符会导致缓存局部性较差;即使复杂度可能相同,这也会使程序运行速度变慢。
标签: python algorithm time-complexity