在刷算法題的時候老是碰到好多題,號稱能夠用hash table來解題。而後就蒙圈了。算法
1.首先,map和hash_map的區別和使用:函數
(1)map底層用紅黑樹實現,hash_map底層用hash_table 實現。因此map的時間複雜度爲O(logn), hash_map爲O(1)。spa
(2)map和hash_map都在stl中,直接include,可是在Mac系統中要#include <ext/hash_map>和 using namespace __gnu_cxx;code
(3)以map爲例來講明使用(hash_map的使用方法和map同樣的):對象
a. 定義: map<int, string> person;blog
b. 插入:person[1000] = "Rambo"; //直接插入,開銷很大,先查找key爲1000的value再插入Rambostring
person.insert(map<int, string>::value_type(1000, "Rambo")); //開銷較小hash
c. 查找:使用find()和count()函數it
find()傳入參數key,返回iterator,若是找不到,返回爲end()。iterator數據類型爲std::pair對象,iterator->first表示key,table
iterator->second表示value。
int key = 123; map<int, string>::iterator it = person.find(key); if(it == person.end()) //沒找到 else //找到了
d.刪除元素: person.erase(iterator it), person.erase(const Key& key); person.clear();
2.hash table:
3.紅黑樹:
這兩部份內容比較複雜,有空再弄吧。