算法导论(CLRS, 2nd) 个人答案 Ch11.1

本文介绍了一种通过两级哈希表实现快速查找、插入、删除操作的方法,并详细说明了其工作原理及步骤,展示了如何利用该方法达到常数级的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

11.1-1:

Perform a linear search on T, worst case is O(m)

 

11.1-2:

0 stands for no elements in the corresponding key, while 1 means the key correspond to some data.

 

11.1-3:

Assumption: besides of the key, the satellite data can also have data to be mapped to a secondary key.

Thus we can consider a case of 2-level hashing table -- the first level to store the primary key, while for the duplicated primary key, we can use the second level to map the secondary key.

Total time is O(2) = O(1)

 

11.1-4:

Create an array A[0 .. n], where A[0] stores the number of elements inserted (thus need to initialize it to 0), and A[1 ..i .. n] stores the i th element's address in the hash table.

In the hash table, for every object inserted, it would also store its inserted order (i.e.: first element? Second? Third? ...), which corresponding to the index of the array A.

When searching for that element, one would use the order i store in that object to check with table A: if A[i] also store the hash of object, then that's the correct element; else that object is actually garbage information.

 

Pseudo code: (name the hash table H)

Initialization:  O(1) -- initialize A[0] = 0; done

Insertion:  O(1) :

  • A[0]++;
  • store that element, as well as A[0]'s value, into the hashing table;
  • A[A[0]] = the hash of that object

Search: O(1): (say search for element x, the hash of x is hash[x])

  • A[H[Hash[x]].indexInA] == Hash[x]?
    • True: return H[Hash[x]]
    • False: return null

Deletion: O(1):(say delete element x)

// basic idea: first find that element, then find its corresponding position in A, change that position's value to be the last inserted value in A, decrease A[0] by 1 (A[0] is the counter of total elements)

  • hx  = Search(x)
  • A[hx.indexInA] = A[A[0]];
  • if(hx==null) return false;
  • H[A[A[0]]].indexInA = hx.indexInA;
  • A[0]--;

 

 

Total Space used < O(2n + n)  // n is the size of that hash table

=> every element's spaced:O(3n)/n = O(3) = O(1)

 

 

 

Reference:

 

CPS 130 Homework 11 - Solutions, retrieved on 20113512:08:15,from:

http://www.cs.duke.edu/courses/summer02/cps130/Homeworks/Solutions/H11-solution.pdf

转载于:https://www.cnblogs.com/flyfy1/archive/2011/03/05/1971502.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值