【发布时间】:2018-08-29 21:55:34
【问题描述】:
我正在尝试解决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),本质上是因为他们遍历数组两次,每个项目的操作数都是恒定的。巧合的是,我在 C++ 中使用 stringstreams 提出了完全相同的方法,但认为它效率不高!
我认为这个sn-p的时间复杂度应该是O(mn),其中m是字符串中的单词数,n是字符串中字母的平均数每个字。这是因为我们遍历输入中的所有元素,在最坏的情况下,mirrorReverse() 再次访问所有元素以进行反转,对于给定的i。
哪个是正确的?
【问题讨论】:
标签: python algorithm time-complexity