performance - 有没有办法降低 O(n^2) 的时间复杂度?

标签 performance algorithm sorting

我做了一个程序(hw),它计算所有单词的频率。 我所有的算法都需要 O(n) 或 O(n log n),但是我的单词计数器需要 O(n^2)

算法如下所示:

for (int i = 0; i < no of elements; i++)
            for (int j = 0; j < no of elements; j++)
                if (the ith word == the jth word)
                {
                    increase that word counter by 1;
                    break;
                }

我使用这种方式的原因是因为单词列表是未排序的。所以我的问题是,使用插入排序或可以按字母顺序对单词列表进行排序的排序是个好主意吗?字符串数组的这种排序方式如何? 单词列表是一个字符串数组,eg:

string words[no of elements]

感谢您的宝贵时间。

最佳答案

为您的单词创建哈希表,然后您的单词计数将为 O(n),因为哈希表查找将为 O(1)。

关于performance - 有没有办法降低 O(n^2) 的时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030908/

相关文章:

php - 依赖于 IF 语句的排序算法

performance - 删除 chrome devTools 中的内存缓存

mysql - 缓慢的 MySQL 查询 : Is there a way to avoid doing a conditional select count for each row with a left join?

algorithm - 一组(非不相交)集合的数据结构

c++ - Sprite 的凸多边形化

java - 将对象的值从 DAO 传递到 2D 数组中的 servlet

r - 日期向量的分位数函数

Javascript包含动态SRC技术="url"

c++ - drawScanlineWithDepth - 优化

java - 在 Hadoop 和 Java 中实现算法