set::insert 的复杂度

complexity of set::insert(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 的复杂度

基础教程推荐