【问题标题】:What's the time complexity of str.count and str.index in a for loopfor循环中str.count和str.index的时间复杂度是多少
【发布时间】: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,我们需要从头到尾统计leletters中出现的次数,然后从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


【解决方案1】:

Letters 大小不变。 s 发生了变化。

index = []
for le in letters: # O(1)
  if s.count(le) == 1: # count is O(n)
    index.push(s.index(le)) # index is O(n)

实际上是 O(2n) 或 O(n)。

【讨论】:

  • 如果字母是固定大小的,那么它就是 O(N)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
相关资源
最近更新 更多