我正在处理一个问题,它要求您在按字典顺序排序的排列中找到字符串的排名。
O(N^2) 很清楚。
一些网站也有O(n) 解决方案。优化的部分基本上是预先填充一个count array
这样的
count[i] 包含 str 中存在且小于 i 的字符数。
我知道这会降低复杂性,但我无法理解我们如何计算这个数组。这是执行此操作的函数(取自链接):
// Construct a count array where value at every index
// contains count of smaller characters in whole string
void populateAndIncreaseCount (int* count, char* str)
{
int i;
for( i = 0; str[i]; ++i )
++count[ str[i] ];
for( i = 1; i < 256; ++i )
count[i] += count[i-1];
}
有人可以提供这个功能的直观解释吗?