[英]How to optimize this simple algorithm further?
Note: this is a programming challenge 注意:这是编程挑战
std::set
.
std::set
。
Input
输入
n
n
n
lines with each j
and k
j
和k
有n
行 Sample input: 样本输入:
5 1 4 2 1 1 6 3 4 1 2
j
is for the operation: 1
to insert k
, 2
to delete k
(if there is a k
), 3
find k
j
用于操作: 1
插入k
, 2
插入删除k
(如果有k
), 3
找k
For j == 3
, output Yes
or No
if k
is in the std::set
. 对于
j == 3
,如果k
在std::set
,则输出Yes
或No
std
functions, but std::find
seems the fastest one, but is still too slow.
std
函数,但std::find
似乎是最快的,但仍然太慢了。
Implementing my own would be even worse, so maybe I missed a function from the library.
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; }
Function Time % over std::find -> 7.410s 370.50% std::count -> 7.881s 394.05% std::binary_search -> 14.050s 702.50%
As you can see my algorithm is 3x slower than the required algorithm. 如您所见,我的算法比所需算法慢3倍。 The bottlenecks are clearly those functions:
瓶颈显然是那些功能:
Function % of total time std::find -> 77.61% std::count -> 80.80% std::binary_search -> 87.59%
But currently I have no better idea than to use std::find
or similar functions. 但目前我没有比使用
std::find
或类似函数更好的想法。 Does someone have a way/idea to optimize my code further? 有人有办法/想法进一步优化我的代码吗? Or are there some obvious bottlenecks that I'm missing?
还是有一些我不知道的明显瓶颈?
You want to use set.find()
and not std::find(set.begin(),set.end())
. 你想使用
set.find()
而不是std::find(set.begin(),set.end())
。
set.find()
will use the set's internal structure to locate the key in O(log(n)) time. set.find()
将使用set的内部结构在O(log(n))时间内定位键。 Whereas std::find
is a linear search, requiring O(n) time, no matter what container type is used. 而
std::find
是线性搜索,无论使用何种容器类型,都需要O(n)时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.