2019-04-04 in class
This commit is contained in:
parent
4a2d768b07
commit
b3ce28dceb
1 changed files with 52 additions and 1 deletions
53
notes.md
53
notes.md
|
@ -173,7 +173,58 @@ Queue has always 1 cell free to avoid confusion with full/empty
|
|||
|
||||
Data structure for fast search
|
||||
|
||||
A way to implement a dictionary is a *Direct-access table*
|
||||
|
||||
## API of dictionary
|
||||
|
||||
- `Insert(D, k)` insert a ket `k` to dictionary `D`
|
||||
- `Delete(D, k)` removes key `k`
|
||||
- `Search(D, k)` tells whether `D` contains a key `k`
|
||||
|
||||
Many different implementations
|
||||
|
||||
## Direct-access table
|
||||
|
||||
Implementation of dictionary
|
||||
- universe of keys = {1,2,...,M}
|
||||
- array `T` of size M
|
||||
- each key has its own position in T
|
||||
|
||||
```python
|
||||
|
||||
def Insert(D, x):
|
||||
D[x] == True
|
||||
|
||||
def Delete(D, x):
|
||||
D[x] == False
|
||||
|
||||
def Search(D, k):
|
||||
return D[x]
|
||||
|
||||
```
|
||||
|
||||
Everything is O(1), but memory complexity is awful.
|
||||
|
||||
Solve this by mapping keys to smaller keys using an hash function.
|
||||
|
||||
Table T is a table many times smaller than the universe and different by a small
|
||||
constant factor from the set of keys stored S.
|
||||
|
||||
Instead of using keys directly, the index returned by the hash function is used.
|
||||
|
||||
**Pigeon hole problem:** More keys (pigeons) in the universe than holes (indexes
|
||||
for table t)
|
||||
|
||||
### Solution
|
||||
|
||||
For every cell in table T don't store True/False but a linked list of keys for
|
||||
each index in the table. This is called *Chained hash table*.
|
||||
|
||||
```python
|
||||
|
||||
def Chained_hash_insert(T, k):
|
||||
return List_insert(T[hash(k)], k)
|
||||
|
||||
def Chained_hash_search(T, k):
|
||||
return List_search(T[hash(k)], k)
|
||||
|
||||
```
|
||||
|
|
Reference in a new issue