c++ 中集合中 find 方法的时间复杂度是多少?

发布于 2024-09-01 02:29:24 字数 177 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明明#如月 2024-09-08 02:29:24

O( log N ) 搜索单个元素。

§23.1.2 表 69

expression  return            note                                   complexity
a.find(k)   iterator;         returns an iterator pointing to an     logarithmic
            const_iterator    element with the key equivalent to k, 
            for constant a    or a.end() if such an element is not 
                              found

O( log N ) to search for an individual element.

§23.1.2 Table 69

expression  return            note                                   complexity
a.find(k)   iterator;         returns an iterator pointing to an     logarithmic
            const_iterator    element with the key equivalent to k, 
            for constant a    or a.end() if such an element is not 
                              found
无法言说的痛 2024-09-08 02:29:24

std::set::find() 的复杂度为 O(log(n)) 只是意味着将有 log(n ) 存储在集合中的对象的比较。

如果比较集合中 2 个元素的复杂度为 O(k) ,则实际复杂度将为 O(log(n)*k)。< br>
例如,在字符串集(k 是最长字符串的长度)的情况下,可能会发生这种情况,因为两个字符串的比较可能意味着比较它们的大部分(或全部)字符(如果它们以相同的前缀开头或者是等)

文档 也有同样的说法:

复杂性

大小为对数。

The complexity of std::set::find() being O(log(n)) simply means that there will be of the order of log(n) comparisons of objects stored in the set.

If the complexity of the comparison of 2 elements in the set is O(k) , then the actual complexity, would be O(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:

Complexity

Logarithmic in size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文