【发布时间】:2012-02-11 05:50:39
【问题描述】:
出于学习目的,我正在编写自己的哈希映射实现。我使用separate chaining with list heads 作为我的主题。
这就是结构的样子:
| 0 | ---> | 11 | ---> | 33 | ---> | -- | ---> | 121 | ---> | TAIL |
| 1 | ---> | 12 | ---> | 34 | ---> | -- | ---> | 122 | ---> | TAIL |
| - |
| - |
| - |
| D-1 | ---> | -- | ---> | -- | ---> | -- | ---> | -- | ---> | TAIL |
它是一个链表数组,其中,
D = 数组的大小,
| 11 | = 带键的元素; 11个AND元素以排序方式插入
算法:
void Insert(key, value):
int bucket = hash_fn(key); // key % D, for now
// accessing this bucket or array-index in array is O(1)
// insert in linked list at the right position
LL[bucket]->insert(new object(key, value))
bool Lookup(key):
int bucket = hash_fn(key); // key % D, for now
// search for key in LL[bucket]
关注:如果很多元素被映射到同一个bucket,搜索不会是O(1),实际上可能会趋向O(n)。
我该如何改进?
【问题讨论】:
标签: performance algorithm data-structures hashmap hashtable