Data structures 在研究数据结构的上下文中初始化数组
我正在阅读CLRS的算法介绍,书中直接地址表部分下有问题11.1练习4:Data structures 在研究数据结构的上下文中初始化数组,data-structures,Data Structures,我正在阅读CLRS的算法介绍,书中直接地址表部分下有问题11.1练习4: We wish to implement a dictionary by using direct addressing on a huge array. At the start, the array entries may contain garbage, and **initializing** the entire array is impractical because of its size. Describe
We wish to implement a dictionary by using direct addressing on a huge array. At
the start, the array entries may contain garbage, and **initializing** the entire array
is impractical because of its size. Describe a scheme for implementing a direct address
dictionary on a huge array. Each stored object should use O(1) space;
the operations SEARCH, INSERT, and DELETE should take O(1) time each; and
initializing the data structure should take O(1) time. (Hint: Use an additional array,
treated somewhat like a stack whose size is the number of keys actually stored in
the dictionary, to help determine whether a given entry in the huge array is valid or
not.)
我知道解决方案只是创建另一个数组,并让它为存在的元素存储指向该数组的指针
但是我对“初始化”在这个上下文中的含义有点困惑。
如果数组未初始化,我们如何访问数据(即使用[i]获取第i个位置的值)
我也不知道为什么这个问题会提出这种内存限制。假设我们可以初始化数组,答案会如何变化?在这种情况下,
初始化
意味着将存储类型的数组中的值设置为NULL
,0
或空值
。其思想是,当为数组分配内存时,所分配内存的内容是随机的,因此数组最终包含随机值。在这种情况下,初始化
值意味着将它们设置为“空”值。在这种情况下,初始化
意味着将存储类型的数组中的值设置为空
,0
或空值
。其思想是,当为数组分配内存时,所分配内存的内容是随机的,因此数组最终包含随机值。在这种情况下,初始化
值意味着将它们设置为“空”值。问题是初始化长度为N的数组——将所有元素设置为一个已知值(如NULL)——需要O(N)个时间
如果您有一个初始化为NULL的数组,那么实现直接访问表就非常容易了--a[i]==NULL意味着i没有值,如果i有值,那么它存储在a[i]中
问题是如何避免O(N)初始化开销。如果数组未初始化,则所有A[i]的初始值可能是任何值。。。那么,如何判断它是真实值还是初始垃圾呢
解决方案不仅仅是创建另一个数组来存储指向原始数组的指针——您必须初始化另一个数组,然后再次浪费O(N)时间
为了完全避免这一成本,你必须更加聪明
制作3个数组A、B和C,并保留字典中值总数的计数N
然后,如果i的值为v: