繁体   English   中英

关于代码片段的时间复杂度

[英]About time complexity of the code snippet

我正在尝试解决一个关于Pramp的问题:

实现一个函数 reverseWords 以最有效的方式反转数组中单词的顺序。

例如: arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e ', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e']

输出:['p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't']

他们给出的类似 Python 的伪代码如下:

function reverseWords(arr):
    # reverse all characters:
    n = arr.length
    mirrorReverse(arr, 0, n-1)

    # reverse each word:
    wordStart = null
    for i from 0 to n-1:
        if (arr[i] == ' '):
            if (wordStart != null):
                mirrorReverse(arr, wordStart, i-1)
                wordStart = null
        else if (i == n-1):
            if (wordStart != null):
                mirrorReverse(arr, wordStart, i)
        else:
            if (wordStart == null):
                wordStart = i

    return arr


# helper function - reverses the order of items in arr
# please note that this is language dependent:
# if are arrays sent by value, reversing should be done in place

function mirrorReverse(arr, start, end):
    tmp = null
    while (start < end):
        tmp = arr[start]
        arr[start] = arr[end]
        arr[end] = tmp
        start++
        end--

他们说时间复杂度是O(n) ,本质上是因为他们遍历数组两次,每个 item 的动作数量不变 顺便说一句,我想出了在 C++ 中使用stringstreams的完全相同的方法,但认为它效率不高!

我认为这个片段的时间复杂度应该是O(mn) ,其中m是字符串中的单词数, n是每个单词中字母的平均数。 这是因为我们遍历输入中的所有元素,在最坏的情况下,对于给定的imirrorReverse()再次访问所有元素以进行反转。

哪个是正确的?

O(n) 中n指的是输入的长度(总字符数),而不是单词的数量。 我怀疑您感到困惑,因为代码在后一种意义上使用了变量n

注意解释:“遍历数组......”。 “数组”由单个字符组成。

这个实现对我来说似乎有点傻; 它更具可读性:

  1. 将字母组连接成单词。
  2. 用一个简单的列表切片反转词序(包括空格)。
  3. 将单词扩展回字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM