开发者

What is time complexity for find method in a set in c++?

开发者 https://www.devze.com 2022-12-30 01:51 出处:网络
set<int> s; s.insert(1); s.insert(2); ... s.insert(n); I wonder how much time it take开发者_Python百科s for s.find(k) where k is a number from 1..n?
set<int> s;

s.insert(1);
s.insert(2);
...
s.insert(n);

I wonder how much time it take开发者_Python百科s for s.find(k) where k is a number from 1..n? I assume it is log(n). Is it correct?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消