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 的复杂度
 
				
         
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				