哈希

哈希表(散列表)通过将关键码映射到表中的某个位置上来存储元素,然后根据关键码来访问元素。

  理想的的情况下,一次直接就能从哈希表中找到要搜索的元素。如果在元素的存储位置与它的关键码之间建立一个对应的函数关系式(散列函数),在插入时,依照这个函数所计算的 存储位置存放。在搜索时对元素的关键码按照同样的函数计算,找到这个存储位置进行读取,若关键码相同则搜索成功。
  通常关键码的集合比散列表地址集合大的多,因此经过散列函数计算后,把不同的关键码映射到同一散列地址上,这就产生了冲突。这时候我们就必须要想办法解决冲突,而且如果冲突太多还会降低搜索的效率。所以我们一般对于给定的关键码集合要选择一个计算简单且地址分布均匀的散列函数。

散列函数的选取方法:

1、直接定址法
取关键字的某个线性函数作为散列函数,Hash(key)=A*key+B;
但是这种方法有很大的缺陷,就是当关键码比较分散时,hash表的所浪费的空间是非常大的。

2、除留余数法
设散列表中允许出现的地址数为m,取一个不大于m但是最接近或等于m的素数p,作为除数(素数作为除数能够减少哈希冲突)。
    hash(key)=key%p;      p<=m;

3、数字分析法
4、平方取中法
5、折叠法
6、随机数法


解决冲突的方法:

一、闭散列法(开地址法):

1、线性探测法
在线性探测中,冲突时通过顺序扫描数组(可以往回找),直到找到空的位置。查找算法也使用了探测法。
hash(key)+0,hash(key)+1,hash(key)+2, ....  hash(key)+i,
但是这种方法有可能引发原始集聚话问题,即导致局部范围大规模发生冲突。

2、二次探测法
hash(key)+0^2,hash(key)+1^2,hash(key)+2^2, ....  hash(key)+i^2。
二次探测法检查了远离原始探测点的单元,这样的话就降低了原始集聚化问题。

3、双散列法
如果用第一个哈希函数解决不了冲突域时,用第二个继续计算,只到冲突域解决为止。双散列法优于二次探测法,


二、开散列法(链地址法):

拉链法:
首先对关键码集合用一个散列函数计算他们存放的位置。将散列表地址相同的元素放到一个集合中,用链表链接起来。


总结:开散列法优于闭散列法,在散列函数中,用除留余数法做散列函数优于其他类型的散列函数。

[cpp]  view plain  copy
  1. #pragma once  
  2. #include<vector>  
  3. using namespace std;  
  4. #include<cmath>  
  5. #include<cstring>  
  6.   
  7.   
  8. namespace HASHTABLE  
  9. {  
  10.     enum Status{ EMPTY, DELETE, EXIST, };  
  11.   
  12.     template<typename K, typename V>  
  13.     struct HashTableNode  
  14.     {  
  15.         K _key;  
  16.         V _value;  
  17.         Status _status;  
  18.         HashTableNode(const K& key = K(), const V& value = V())  
  19.             :_key(key)  
  20.             , _value(value)  
  21.             , _status(EMPTY)  
  22.         {}  
  23.     };  
  24.   
  25.     template<typename K>  
  26.     struct __HashFunc  
  27.     {  
  28.         size_t operator()(const K& key)  
  29.         {  
  30.             return key;  
  31.         }  
  32.     };  
  33.   
  34.     template<>                      //由于string用的也比较多,所以将string实现成偏特化  
  35.     struct __HashFunc<string>  
  36.     {  
  37.         size_t operator()(const string& str)  
  38.         {  
  39.             size_t num = 0;  
  40.             int len =(int)str.size();  
  41.             int i = 0;  
  42.             while (len--)  
  43.             {  
  44.                 num += str[i] * (int)pow(128.0, len);  
  45.                 i++;  
  46.             }  
  47.             return num;  
  48.         }  
  49.     };  
  50.   
  51.   
  52.     //线性探测           //二次探测  
  53.     template<typename K, typename V,class HashFunc=__HashFunc<K>>  
  54.     class HashTable  
  55.     {  
  56.         typedef HashTableNode<K, V> Node;  
  57.     public:  
  58.         HashTable()  
  59.             :_size(0)  
  60.         {  
  61.             _table.resize(_GetPrime(0));  
  62.         }  
  63.   
  64.         HashTable(const HashTable<K, V,HashFunc>& hash)  
  65.         {  
  66.             size_t newsize = hash._table.size();           //得到hash的大小  
  67.             _table.resize(newsize);                       //先扩容  
  68.   
  69.             for (size_t i = 0; i <_table.size(); i++)     //将hash表中的关键码拷贝到到新表中  
  70.             {  
  71.                 if (hash._table[i]._status == EXIST)  
  72.                 {  
  73.                     _table[i]._key = hash._table[i]._key;  
  74.                     _table[i]._value = hash._table[i]._value;  
  75.                     _table[i]._status = EXIST;  
  76.                 }  
  77.             }  
  78.             _size = hash._size;  
  79.         }  
  80.   
  81.         HashTable<K, V, HashFunc>& operator=(const HashTable<K, V, HashFunc>& hash)  
  82.         {  
  83.             if (this != &hash)  
  84.             {  
  85.                 HashTable<K, V, HashFunc> h(hash);  
  86.                 Swap(h);  
  87.             }  
  88.             return *this;  
  89.         }  
  90.   
  91.         Node* Find(const K& key)  
  92.         {  
  93.             int index = _HashFunc(key);  
  94.             if (index >= 0)  
  95.             {  
  96.                 int start = index;        //记录第一次计算的位置  
  97.                 while (_table[index]._status != EMPTY)      //这个位置要不为空  
  98.                 {  
  99.                     if (_table[index]._key == key)  
  100.                     {  
  101.                         //如果已经找到这个关键码,还要判断这个关键码的状态  
  102.                         if (_table[index]._status == EXIST)  
  103.                             return &_table[index];  
  104.                     }  
  105.                     index++;  
  106.                     if (index == _table.size())  
  107.                         index = 0;  
  108.   
  109.                     if (index == start)                    //如果此时表中都不为空,但是有标记删除的,所以还有可能再找到起始位置  
  110.                         break;                             //这种情况是找不到的  
  111.                 }  
  112.             }  
  113.             return NULL;  
  114.         }  
  115.   
  116.         bool Insert(const K& key, const V& value)  
  117.         {  
  118.             _CheckCapacity();               //先判断需不需要增加表的长度  
  119.             int index = _HashFunc(key);  
  120.             if (index >= 0)         //如果已经找到了在hash中映射的地址  
  121.             {  
  122.                 while (_table[index]._status == EXIST)  //先找到这个不为存在的位置,由于负载因子的存在,所以不可能全都是EXIST  
  123.                 {  
  124.                     index++;                        //线性探测可以改为二次探测,双散列也可以  
  125.                     if (index == _table.size())  
  126.                         index = 0;  
  127.                 }  
  128.                 //如果这个位置不是存在的状态,再插入  
  129.   
  130.                 _table[index]._key = key;  
  131.                 _table[index]._value = value;  
  132.                 _table[index]._status = EXIST;  
  133.                 _size++;  
  134.                 return true;  
  135.             }  
  136.             return false;  
  137.         }  
  138.   
  139.         bool Remove(const K& key)  
  140.         {  
  141.             //要删除之前先要找到这个要删除的关键码  
  142.             Node* del = Find(key);  
  143.             if (del)                 //如果已经找到了要删除的关键码,则采用懒惰删除  
  144.             {  
  145.                 del->_status = DELETE;  
  146.                 _size--;                   //元素的个数要减一  
  147.                 return true;  
  148.             }  
  149.             return false;  
  150.         }  
  151.   
  152.         void Swap(HashTable<K, V, HashFunc>& table)  
  153.         {  
  154.             if (this != &table)         //不是自己与自己交换  
  155.             {  
  156.                 _table.swap(table._table);  
  157.                 swap(_size, table._size);  
  158.             }  
  159.         }  
  160.     protected:  
  161.         int _HashFunc(const K& key)  
  162.         {  
  163.             if (_table.size())  
  164.             {   //生成一个匿名对象,调用仿函数  
  165.                 return HashFunc()(key)%_table.size();  
  166.             }  
  167.             return -1;  
  168.         }  
  169.   
  170.         static unsigned _GetPrime(const unsigned long size)  
  171.         {  
  172.             const int _PrimeSize = 28;  
  173.             static const unsigned long _PrimeList[_PrimeSize] =  
  174.             {  
  175.                 53ul, 97ul, 193ul, 389ul, 769ul,  
  176.                 1543ul, 3079ul, 6151ul, 12289ul, 24593ul,  
  177.                 49157ul, 98317ul, 196613ul, 393241ul,  
  178.                 786433ul,  
  179.                 1572869ul, 3145739ul, 6291469ul, 12582917ul,  
  180.                 25165843ul,  
  181.                 50331653ul, 100663319ul, 201326611ul, 402653189ul,  
  182.                 805306457ul,  
  183.                 1610612741ul, 3221225473ul, 4294967291ul  
  184.             };  
  185.             for (size_t i = 0; i <_PrimeSize; i++)     //返回一个比当前hash表大的素数  
  186.             {  
  187.                 if (size < _PrimeList[i])  
  188.                     return _PrimeList[i];  
  189.             }  
  190.             return _PrimeList[_PrimeSize - 1];   //否则返回最后一个值  
  191.         }  
  192.   
  193.         void _CheckCapacity() //如果载荷因子大于0.8,则这时候插入的效率就很低,所以这时候就要增大表的大小  
  194.         {  
  195.             //载荷因子等于元素的个数除以表的长度  
  196.             if (_table.size() == 0 || _size * 10 / _table.size() >= 8)   //这时候插入的效率很低,就要增加hash表的长度  
  197.             {  
  198.                 //由于hash表已经扩容,所以要重新计算表中元素的哈希地址  
  199.                 HashTable<K, V, HashFunc> hash;           //先创建一个临时的表  
  200.                 size_t newsize = _GetPrime(_table.size());  
  201.                 hash._table.resize(newsize);  
  202.                 for (size_t i = 0; i <_table.size(); i++)     //将旧的表中的关键码拷贝到hash中  
  203.                 {  
  204.                     if (_table[i]._status == EXIST)  
  205.                     {  
  206.                         hash.Insert(_table[i]._key, _table[i]._value);  
  207.                     }  
  208.                 }  
  209.                 //交换两个hash表  
  210.                 Swap(hash);  
  211.             }  
  212.         }  
  213.     private:  
  214.         vector<Node> _table;  
  215.         size_t _size;  
  216.     };  
  217. }  
  218.   
  219.   
  220.   
  221.   
  222.   
  223. namespace HashTable_link  
  224. {  
  225.     template<typename K,typename V>  
  226.     struct HashTableNode  
  227.     {  
  228.         K _key;  
  229.         V _value;  
  230.         HashTableNode<K, V>* _next;  
  231.         HashTableNode(const K& key=K(),const V& value=V())  
  232.             :_key(key)  
  233.             , _value(value)  
  234.             , _next(NULL)  
  235.         {}  
  236.     };  
  237.   
  238.     template<class K>             //为了将得到hash地址统一起来,使用仿函数,将整型的时候默认实现出来  
  239.     struct __HashFunc               //仿函数,将关键值转换成整型数值  
  240.     {  
  241.         size_t operator()(const K& key)  
  242.         {  
  243.             return key;  
  244.         }  
  245.     };  
  246.   
  247.     //由于string也是常用的类型,所以对string进行偏特化  
  248.     template<>  
  249.     struct __HashFunc<string>  
  250.     {  
  251.         size_t operator()(const string& str)  
  252.         {  
  253.             size_t num = 0;  
  254.             for (int i = 0; i < (int)str.size(); i++)  
  255.             {  
  256.                 num += num * 131 +str[i];  
  257.             }  
  258.             return num;  
  259.         }  
  260.     };  
  261.   
  262.     template<typename K,typename V,class HashFunc=__HashFunc<K>>       //仿函数默认类型是K  
  263.     class HashTable  
  264.     {  
  265.         typedef HashTableNode<K, V> Node;  
  266.     public:  
  267.         HashTable()  
  268.             :_size(0)  
  269.         {  
  270.             _tables.resize(_GetPrime(0));  
  271.         }  
  272.   
  273.         HashTable(const HashTable<K, V,HashFunc>& hash)  
  274.         {  
  275.             _tables.resize(hash._tables.size());  
  276.             for (int i = 0; i <(int)hash._tables.size(); i++)             //将当前表的内容导入到新表  
  277.             {  
  278.                 Node* cur = hash._tables[i];  
  279.                 while (cur)  
  280.                 {  
  281.                     Insert(cur->_key, cur->_value);  
  282.                     cur = cur->_next;  
  283.                 }  
  284.             }  
  285.         }  
  286.   
  287.         HashTable<K, V, HashFunc>& operator=(const HashTable<K, V, HashFunc>& hash)  
  288.         {  
  289.             if (this != &hash)           //如果不是自赋值  
  290.             {  
  291.                 HashTable<K, V, HashFunc> tmp(hash);  
  292.                 Swap(tmp);  
  293.             }  
  294.             return *this;  
  295.         }  
  296.   
  297.         ~HashTable()  
  298.         {  
  299.             for (int i = 0; i <(int)_tables.size(); i++)             //将当前表的内容导入到新表  
  300.             {  
  301.                 Node* cur =_tables[i];  
  302.                 Node* del = NULL;  
  303.                 while (cur)  
  304.                 {  
  305.                     del = cur;  
  306.                     cur = cur->_next;  
  307.                     delete del;  
  308.                 }  
  309.             }  
  310.         }  
  311.   
  312.         Node* Find(const K& key)  
  313.         {  
  314.             int index = _HashFunc(key);  
  315.             if (index >= 0)  
  316.             {  
  317.                 Node* cur = _tables[index];  
  318.                 while (cur)  
  319.                 {  
  320.                     if (cur->_key == key)  
  321.                     {  
  322.                         return cur;  
  323.                     }  
  324.                     cur = cur->_next;  
  325.                 }  
  326.   
  327.             }  
  328.             return NULL;  
  329.         }  
  330.   
  331.         bool Insert(const K& key,const V& value)  
  332.         {  
  333.             _CheckSize();                      //先判断表的载荷因子是否已经达到1,达到1的话就扩容  
  334.   
  335.             Node* ret = Find(key);  
  336.             if (ret== NULL)                  //如果要插入的key不存在的,则可以插入  
  337.             {  
  338.                 int index = _HashFunc(key);  
  339.                 Node* cur = new Node(key,value);  
  340.                 cur->_next = _tables[index];  
  341.                 _tables[index] = cur;  
  342.                 _size++;  
  343.                 return true;  
  344.             }  
  345.             return false;  
  346.         }  
  347.   
  348.         bool Remove(const K& key)  
  349.         {  
  350.             int index = _HashFunc(key);  
  351.             if (index >= 0)  
  352.             {  
  353.                 Node* prev = NULL;  
  354.                 Node* cur = _tables[index];  
  355.                 while (cur)  
  356.                 {  
  357.                     if (cur->_key ==key)  
  358.                     {  
  359.                         if (prev == NULL)  
  360.                         {  
  361.                             _tables[index] = cur->_next;         //删除第一个结点  
  362.                         }  
  363.                         else  
  364.                         {  
  365.                             prev->_next = cur->_next;  
  366.                         }  
  367.                         delete cur;  
  368.                         _size--;  
  369.                         return true;  
  370.                     }  
  371.                     prev = cur;  
  372.                     cur = cur->_next;  
  373.                 }  
  374.             }  
  375.             return false;  
  376.         }  
  377.   
  378.         void Swap(HashTable<K, V, HashFunc>& hash)  
  379.         {  
  380.             _tables.swap(hash._tables);  
  381.             swap(_size,hash._size);  
  382.         }  
  383.   
  384.     protected:  
  385.         static unsigned _GetPrime(const unsigned long size)  
  386.         {  
  387.             const int _PrimeSize = 28;  
  388.             static const unsigned long _PrimeList[_PrimeSize] =  
  389.             {  
  390.                 53ul, 97ul, 193ul, 389ul, 769ul,  
  391.                 1543ul, 3079ul, 6151ul, 12289ul, 24593ul,  
  392.                 49157ul, 98317ul, 196613ul, 393241ul,  
  393.                 786433ul,  
  394.                 1572869ul, 3145739ul, 6291469ul, 12582917ul,  
  395.                 25165843ul,  
  396.                 50331653ul, 100663319ul, 201326611ul, 402653189ul,  
  397.                 805306457ul,  
  398.                 1610612741ul, 3221225473ul, 4294967291ul  
  399.             };  
  400.             for (size_t i = 0; i <_PrimeSize; i++)     //返回一个比当前hash表大的素数  
  401.             {  
  402.                 if (size < _PrimeList[i])  
  403.                     return _PrimeList[i];  
  404.             }  
  405.             return _PrimeList[_PrimeSize - 1];   //否则返回最后一个值  
  406.         }  
  407.   
  408.         void _CheckSize()  
  409.         {  
  410.             if (_tables.size()==0||_size/_tables.size() == 1)       //如果表的长度为0,或者载荷因子为1,则先扩容  
  411.             {  
  412.                 HashTable<K, V, HashFunc> hash;                            //创建一个临时的新hash表  
  413.                 hash._tables.resize(_GetPrime(_tables.size()));  
  414.                 for (int  i = 0; i <(int)_tables.size(); i++)             //将当前表的内容导入到新表  
  415.                 {  
  416.                     Node* cur = _tables[i];  
  417.                     while (cur)  
  418.                     {  
  419.                         hash.Insert(cur->_key,cur->_value);  
  420.                         cur = cur->_next;  
  421.                     }  
  422.                 }  
  423.                 Swap(hash);            //交换两个表的内容  
  424.             }  
  425.         }  
  426.   
  427.         int _HashFunc(const K& key)  
  428.         {  
  429.             if (_tables.size())  
  430.             {  
  431.                 return (HashFunc()(key))%_tables.size();  //先构造一个匿名对象,再调用仿函数  
  432.             }  
  433.             return -1;  
  434.         }  
  435.     private:  
  436.         vector<Node*> _tables;  
  437.         size_t _size;  
  438.     };  
  439. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值