如何进一步优化这个简单的算法
How to optimize this simple algorithm further?
注意:这是一个编程挑战
此挑战需要使用
std::set
。
输入
- 一个数字
n
n
线,每个j
和k
样本输入:
5
1 4
2 1
1 6
3 4
1 2
j
用于操作:1
插入k
,2
删除k
(如果有k
),3
查找k
对于j == 3
,如果k
在std::set
中,则输出Yes
或No
。
我制作了不同版本的算法,但都太慢了。我尝试了不同的
std
功能,但std::find
似乎是最快的,但仍然太慢。实现我自己的函数会更糟糕,所以可能我错过了库中的一个函数。我真的不知道如何进一步优化它。目前我有这个:
int main()
{
std::set<int> set{};
int Q = 0;
std::cin >> Q;
int type = 0;
int x = 0;
for (int i = 0; i < Q; ++i)
{
std::cin >> type;
std::cin >> x;
if (type == 1)
set.insert(x);
else if (type == 2)
set.erase(x);
else if (type == 3)
std::cout << (std::find(std::begin(set), std::end(set), x) != std::end(set) ? "Yes" : "No") << 'n';
//Condition may be std::find, std::count or std::binary_search
}
return 0;
}
挑战要求它在2秒内完成。以下是我的结果:
Function Time % over
std::find -> 7.410s 370.50%
std::count -> 7.881s 394.05%
std::binary_search -> 14.050s 702.50%
正如你所看到的,我的算法比要求的算法慢3倍。瓶颈显然是那些功能:
Function % of total time
std::find -> 77.61%
std::count -> 80.80%
std::binary_search -> 87.59%
但目前我没有比使用std::find
或类似函数更好的想法了。有人有办法/想法来进一步优化我的代码吗?还是我遗漏了一些明显的瓶颈?
您希望使用set.find()
而不是std::find(set.begin(),set.end())
。
set.find()
将使用集合的内部结构来定位O(log(n))时间中的密钥。而std::find
是线性搜索,无论使用何种容器类型,都需要O(n)时间。
相关文章:
- 对多个(可能)重叠范围进行分区的最简单算法
- 学习数据结构和算法的简单方法
- 使用简单的暴力算法找到数组中最大的4个元素
- 使用 Prim 算法计算最小生成树:如何使其简单?
- 使用 c++17 算法并行化简单循环
- 与CUDA上的GPU上的简单算法并行
- 在C 中编写一个简单的排序算法以及伪代码版本
- 为什么对于简单的 StereoBM 算法,我的代码比 opencv 慢得多
- C++简单的凯撒密码算法
- 用于简单 2D 自上而下的车辆碰撞物理的算法
- 简单过程生成2D城市的算法
- 如何进一步优化这个简单的算法
- 简单的三角函数算法,用于计算定点数的 sin() 和 cos()
- 从文本文件中简单读取算法不起作用
- 无锁简单隔离存储算法
- c++中简单的通配符搜索算法
- OpenGL中粒子发射器的简单三维烟雾算法
- 简单的拼写检查算法
- 调试使用广度优先搜索(BFS)的简单图算法
- 帮助我理解这个算法(简单)