c++ 中集合中 find 方法的时间复杂度是多少?
set<int> s;
s.insert(1);
s.insert(2);
...
s.insert(n);
我想知道 s.find(k)
需要多少时间,其中 k
是 1..n 中的数字? 我假设它是log(n)。正确吗?
set<int> s;
s.insert(1);
s.insert(2);
...
s.insert(n);
I wonder how much time it takes for s.find(k)
where k
is a number from 1..n?
I assume it is log(n). Is it correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
O( log N ) 搜索单个元素。
§23.1.2 表 69
O( log N ) to search for an individual element.
§23.1.2 Table 69
std::set::find()
的复杂度为O(log(n))
只是意味着将有log(n )
存储在集合
中的对象的比较。如果比较集合中 2 个元素的复杂度为
O(k)
,则实际复杂度将为O(log(n)*k)
。< br>例如,在字符串集(k 是最长字符串的长度)的情况下,可能会发生这种情况,因为两个字符串的比较可能意味着比较它们的大部分(或全部)字符(如果它们以相同的前缀开头或者是等)
文档 也有同样的说法:
The complexity of
std::set::find()
beingO(log(n))
simply means that there will be of the order oflog(n)
comparisons of objects stored in theset
.If the complexity of the comparison of 2 elements in the set is
O(k)
, then the actual complexity, would beO(log(n)∗k)
.this can happen for example in case of set of strings (k would be the length of the longest string) as the comparison of 2 strings may imply comparing most of (or all) of their characters (if they start with the same prefix or are equal)
The documentation says the same: