我想了解为什么Rabin-Karp算法的最坏情况运行时间是O(nm),而平均情况是O(n+m)。请有人帮助我吗?
维基百科 很好地解释了该算法的时间复杂度。
可以说,哈希计算函数 的有效性(指能够以恒定时间动态重复使用已计算的哈希值的能力)是算法时间复杂度计算中的一个决定性因素。
让我们看看哈希计算如何造成这种差异。
当以下情况时,时间复杂度为O(nm)
:
call hash(s[1..m]) // O(m) additive
for index from 1 to n-m+1 // O(n)
//Code to check if substring matches
call hash(s[index+1..index+m]) // Inefficient hash function, takes O(m), just like naive string matching
与 O(nm)
相比,相加的 O(m)
往往被大部分人忽略。
给定,O(m) + O(n)*O(m)
= O(nm)
当:
时间复杂度为 O(n+m)
的情况下:
call hash(s[1..m]) // O(m) additive
for index from 1 to n-m+1 // O(n)
//Code to check if substring matches
call hash(s[index+1..index+m]) //Efficient hash function which takes only O(1), applies Rolling Hashing
Giving, O(m) + O(n)*O(1)
= O(m) + O(n)
= O(m+n)
m<n
,因此O(n+m)就是O(n)。阅读任何关于大O符号的标准文本,以便理解这一点,如果不明显的话。 - rici