【问题标题】:Time complexity of finding a string in an unordered set of strings在无序字符串集中查找字符串的时间复杂度
【发布时间】:2020-07-31 16:56:38
【问题描述】:

http://www.cplusplus.com/reference/unordered_set/unordered_set/find/

对于 unordered_set,在 unordered_set 中查找的时间复杂度平均为常数。 如果我有一个 unordered_set 字符串,那么在该集合中找到一个字符串的时间复杂度是多少? 它会是常数还是 O(字符串的长度)?

【问题讨论】:

  • 重点是 cppreference.com 比您链接的来源更准确、更有信誉。
  • 是常量还是 O(字符串的长度)? -- 必须计算您要搜索的字符串的哈希值。查看std::hash<std::string> 的实现。

标签: c++ string stl find unordered-set


【解决方案1】:

std::unordered_set 实现为哈希表。其find 方法的平均复杂度为O(1),最坏情况复杂度为O(set.size()) 键比较,由[tab:container.hash.req] 指定。


默认情况下,std::unordered_set&lt;std::string&gt; 使用operator== 比较键,因此每个键比较在[string.view.ops] 中指定的O(str.size()) 中运行(operator==(const std::string&amp;, const std::string&amp;) 定义为等效于std::string_view(str1) == std::string_view(str2),它定义为相当于std::string_view(str1).compare(std::string_view(str2) == 0)。

对于std::unordered_set&lt;std::string&gt;,容器必须计算要查找的字符串的哈希值。默认情况下,它为此使用std::hash&lt;std::string&gt;。该标准没有为std::hash&lt;std::string&gt; 指定任何复杂性要求,但很可能是O(str.size())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2018-01-06
    相关资源
    最近更新 更多