随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(209)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示