【问题标题】:Why std::map::emplace_hint's time complexity is constant providing correct hint为什么 std::map::emplace_hint 的时间复杂度恒定提供正确的提示
【发布时间】:2020-12-11 06:17:46
【问题描述】:

来自cppreference,据说std::map::emplace_hint的复杂度是:

Complexity
Logarithmic in the size of the container in general, but amortized constant if the new element is inserted just before hint.

如果我们提供一个好的提示,为什么它是恒定的?

【问题讨论】:

  • 您要制作文档吗?

标签: c++ stl


【解决方案1】:

std::map 是一棵红黑树,为了在std::map 中插入/放置一个新元素,我们需要:

  1. 找到插入/放置新元素的合适位置 - O(lgN)
  2. 重新着色和旋转节点以保持红黑树属性。 - O(1)

如果提供了很好的提示,则搜索部分(#1)已经完成,对于#2,有4 scenarios,每个都是 O(1)

所以在适当的提示下,std::map::emplace_hint 是 O(1)

【讨论】:

  • nitpick: std::map 没有被指定为红黑树,尽管这是一个常见的实现。
猜你喜欢
  • 2012-04-15
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多