SOLUTION
Compare and contrast Hash Table vs. STL map
在hash_table中value通过使用哈希函数产生的关键字来存储。因此在hash table中值不是以有序的方式来存储。此外,由于使用key找到下标来存储value,所以插入和查找能够在O(1)时间内完成。在hashtable中必须处理潜在的冲突。
In a hash table, a value is stored by applying hash function on a key. Thus, values are not
stored in a hash table in sorted order. Additionally, since hash tables use the key to find the
index to store the value, an insert/lookup can be done in O(1) time. One must also handle
potential collisions in a hash table.
在STL map中,插入 的key/value对是以key来排序的。map使用树来存储values,插入的key/value对以key按序存储。所以查找和插入时间需要O(log N) 。同时也没有必要进行冲突处理。
STL map在如下情况可以很好的工作:
最大,最小元素的查找
按序输出元素
In an STL map, insertion of key/value pair is in sorted order of key. It uses a tree to store
values, which is why an O(log N) insert/lookup is required. There is also no need to handle
collisions. An STL map works well for things like:
»» find min element
»» find max element
»» print elements in sorted order
»» find element or the biggest number smaller than it
hash table的实现
1需要较好的hash函数保证hash值分布一致。
2定义冲突处理的方法:链表(表项密度大时)开放定址(稀疏表项)
How is a hash table implemented?
1. A good hash function is required, (e.g.: operation % prime number) to ensure the hash
values are uniformly distributed.
2. A collision resolving method is also needed: chaining (good for dense table entries),
probing (good for sparse table entries), etc.
3动态增加或者减少hash table的大小
3. Implement methods to dynamically increase or decrease the hash table size on a
given criterion. For example, when the [number of elements] by [table size] ratio is
greater than fixed threshold, increase the hash table size by creating new hash table
and transfer the entries from old table to new table by computing the index using new
hash function.
数据很少时可以可以考虑STL map。时间可以忽略。
What can be used instead of hash table, if number of inputs is small?
You can use an STL map. Although this takes O(lg n) time, since the number of inputs is small,
this time is negligible.