2014-04-25 19:29
题目:对比一下哈希表和STL中的map的区别,哈希表如何实现?如果数据规模比较小,可以用什么来代替哈希表?
解法:哈希表可以理解为一堆桶,每个桶都有唯一的id,桶里可以存至少一个元素;而STL的map是一棵平衡二叉搜索树,每个节点存一个元素。还有很多细节要说,如果on-site面试的话,也许可以写写画画,或者直接写出一个简单的哈希表来,参考unordered_map。如果数据规模小的话,直接用数组就可以了。之前有一道题让实现一个哈希表,所以在这儿就不重复写一次了。
代码:
1 // 13.2 Expain your understanding on hash table and STL map. If data scale is small, what can be used to replace hash table? 2 // Answer: 3 // Hash table is a data structure which holds item in buckets. Every bucket has a hash number, which is computed by a hashFunction(). 4 // When inserting or searching in the hash table, the key is passed to the hashFunction() to calculate the corresponding hash number, that will decide which bucket is to hold this item. 5 // While there will be multiple elements with the same hash number, known as collision, the hash table has to be equipped with probing strategy, which decides where the next proper position to hold the item is. 6 // Three important properties about hash table: 7 // 1. == operator 8 // 2. hashFunction() 9 // 3. probing strategy, such as linear, quadratic, polynomial, chaining and so on 10 // A single operation could reach O(1) time, but collision will require extra probing time. 11 // 12 // STL map is a red-black tree, which is a high-balanced binary search tree. 13 // The elements in STL map is sorted, as the nodes in a BST is inserted based on comparison. 14 // A single operation could reach O(log(n)) time. 15 // Two important properties aboutt STL map: 16 // 1. < operator 17 // 2. red-black tree 18 int main() 19 { 20 return 0; 21 }