complexity of set::insert(set::insert 的复杂度)
问题描述
我已经阅读到集合中的插入操作只需要 log(n) 时间.这怎么可能?
I have read that insert operation in a set takes only log(n) time. How is that possible?
要插入,首先我们要在排序后的数组中找到新元素必须位于的位置.使用二分查找需要 log(n).然后要插入到那个位置,它后面的所有元素都应该向右移动一个位置.又需要n次.
To insert, first we have find the location in the sorted array where the new element must sit. Using binary search it takes log(n). Then to insert in that location, all the elements succeeding it should be shifted one place to the right. It takes another n time.
我的怀疑是基于我的理解,即 set 是作为数组实现的,并且元素按排序顺序存储.如果我的理解有误,请纠正我.
My doubt is based on my understanding that set is implemented as an array and elements are stored in sorted order. Please correct me if my understanding is wrong.
推荐答案
std::set
通常实现为红黑二叉搜索树.在这种数据结构上插入的最坏情况是 O(log(n)) 复杂度,因为树保持平衡.
std::set
is commonly implemented as a red-black binary search tree. Insertion on this data structure has a worst-case of O(log(n)) complexity, as the tree is kept balanced.
这篇关于set::insert 的复杂度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:set::insert 的复杂度


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01