【发布时间】:2019-08-15 16:42:23
【问题描述】:
我正在学习算法的时间复杂度。我不明白为什么以下代码的时间复杂度为 O(n)。
这是来自 leetcode 问题的解决方案https://leetcode.com/problems/first-unique-character-in-a-string/discuss/86351/Python-3-lines-beats-100-(~-60ms)-!
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(le) for le in letters if s.count(le) == 1]
return min(index) if len(index) > 0 else -1
我认为这个算法有 O(n^2),这是我的逻辑:
对于letters中的每一个le,我们需要从头到尾统计le在letters中出现的次数,然后从letters中找到le的索引从头到尾。
我们基本上遍历letters,也就是O(n)。对于每次迭代,我们都在做count,这是 O(n) 和 index,也是 O(n)。所以,它应该是 O(iteration)*(O(count) + O(index)) = O(n) * (O(n) + O(n)) = O(2n^2) => O(n ^2)
我的逻辑有什么问题?
编辑:
我想我知道我的逻辑有什么问题。 letters 只有 26 个字母,所以它是一个常数时间。
【问题讨论】:
-
实际上,遍历字母是一个常数时间,因为大小永远不会改变
标签: python algorithm time-complexity big-o