本文已参与「新人创作礼」活动,一起开启掘金创作之路。
哈希冲突的解决方案
1. 闭散列
闭散列也叫开放定址法。
当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key
存放到冲突位置中的“下一个” 空位置中去。
线性探测
比如现在需要插入元素44
,先通过哈希函数计算哈希地址,hashAddr
为4
,因此44
理论上应该插在该位置,但是该位置已经放了值为4
的元素,即发生哈希冲突。
线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。
- 【插入】 插入通过哈希函数获取待插入元素在哈希表中的位置。
如果该位置中没有元素则直接插入新元素。
如果该位置中有元素发生哈希冲突,使用线性探测找到下一个空位置,插入新元素。
2. 【删除】
删除采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。
(比如删除元素4
,如果直接删除掉,44
查找起来可能会受影响。因此线性探测采用标记的伪删除法来删除一个元素,设置状态值的方法。)
enum State{
EMPTY, //此位置为 空
EXIST, //此位置为 已有元素
DELETE //此位置为 已经删除
};
线性探测的实现
// 注意:假如实现的哈希表中元素唯一,即key相同的元素不再进行插入
// 为了实现简单,此哈希表中我们将比较直接与元素绑定在一起
enum State {
EMPTY, //此位置为 空
EXIST, //此位置为 已有元素
DELETE //此位置为 已经删除
};
template<class K, class V>
class HashTable{
struct Elem{
pair<K, V> _val;
State _state;
};
public:
HashTable(size_t capacity = 3)
: _ht(capacity),
_size(0)
{
for (size_t i = 0; i < capacity; ++i)
_ht[i]._state = EMPTY;
}
bool Insert(const pair<K, V>& val){
// 检测哈希表底层空间是否充足
// _CheckCapacity();
size_t hashAddr = HashFunc(key);
// size_t startAddr = hashAddr;
while (_ht[hashAddr]._state != EMPTY){
if (_ht[hashAddr]._state == EXIST && _ht[hashAddr]._val.first == key)
return false;
hashAddr++;
if (hashAddr == _ht.capacity())
hashAddr = 0;
/*
// 转一圈也没有找到,注意:动态哈希表该种情况可以不用考虑,哈希表中元素个数到达
一定的数量,哈希冲突概率会增大,需要扩容来降低哈希冲突,因此哈希表中元素是不会存满的
if(hashAddr == startAddr)
return false;
*/
}
// 插入元素
_ht[hashAddr]._state = EXIST;
_ht[hashAddr]._val = val;
_size++;
return true;
}
int Find(const K& key){
size_t hashAddr = HashFunc(key);
while (_ht[hashAddr]._state != EMPTY){
if (_ht[hashAddr]._state == EXIST && _ht[hashAddr]._val.first == key)
return hashAddr;
hashAddr++;
}
return hashAddr;
}
bool Erase(const K& key){
int index = Find(key);
if (index != -1){
_ht[index]._state = DELETE;
_size--;
return true;
}
return false;
}
private:
size_t HashFunc(const K& key){
return key % _ht.capacity(); //除留余数法,闭散列的核心,也是局限性所在
//因为必须给定一个整型家族的key值,如果传入字符串就无法判断
}
private:
vector<Elem> _ht;
size_t _size;
};
上述哈希表还存在以下的缺陷:
- 只能存储
key
为整型的元素,其他类型无法解决,例如string
对象。 【解决方案】: 构造一个仿函数,重载operator()
对非整型元素进行转化即可。
//仿函数
template<class K>
struct HashFunc{
const K& operator()(const K& key){
return key;
}
};
//针对字符串key值的【模板特化】
template<>
struct HashFunc<string>{
size_t BKDRHash(const char* str){
size_t hash = 0;
while (*str){
hash = hash * 131 + *str;
++str;
}
return hash;
}
size_t operator()(const string& s){
return BKDRHash(s.c_str());
}
};
为了实现简单,此哈希表中我们将比较直接与元素绑定在一起
template<class K, class V, class HF>
class HashTable{
// ……
private:
size_t HashFunc(const K& key){
return HF()(key)%_ht.capacity();
}
- 除留余数法,最好对一个素数取模,每次快速取一个类似两倍关系的素数又是一个问题。 【解决方案】:给定一个素数表查找算法即可,获取到下一个素数、
const int PRIMECOUNT = 28;
const size_t primeList[PRIMECOUNT] ={
// ul: unsigned long
53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul
};
size_t GetNextPrime(size_t prime){
size_t i = 0;
for (; i < PRIMECOUNT; ++i){
if (primeList[i] > prime)
return primeList[i];
}
return primeList[i];
}
- 增容时机,如何增容还需要另外考虑。
(
载荷因子 = 表中元素个数 / 表长度
)
【方案】:对于开放定址法,载荷因子应控制在0.7 ~ 0.8
以下,超过就需要增容。
线性探测的优缺点分析
优点 | 缺点 |
---|---|
实现简单 | 一旦发生哈希冲突,所有的冲突连在一起,容易产生数据“堆积”,即不同关键码占据了可利用的空位置,使得寻找某关键码的位置需要许多次比较,导致搜索效率降低。 |
线性探测的缺点的优化方案为另一种方法:二次探测。
二次探测
线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就 是挨着往后逐个去找。
因此二次探测为了避免该问题,找下一个空位置的方法为: A(i)= (A(0) + i^2^ ) % m或者:A(i)= (A(0) - i^2^ ) % m。其中:i = 1,2,3…
是通过散列函数Hash(x)
对元素的关键码 key
进行计算得到的位置,m
是表的大小。
研究表明: 当表的长度为质数且表装载因子
a
不超过0.5
时,新的表项一定能够插入,而且任何一个位置都不会被探查两次。因此只要表中有一半的空位置,就不会存在表满的问题。 在搜索时可以不考虑表装满的情况,但在插入时必须确保表的装载因子a
不超过0.5
,如果超出必须考虑增容。
因此:闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。
闭散列代码整合
namespace closehash{ //闭散列
enum State{ //三种状态
EXIST,
EMPTY,
DELETE,
};
template<class T>
struct HashStruct{
T _v;
State _state;
};
template<class K, class T>
class HashTable{
typedef HashStruct<T> HashStruct;
public:
bool Insert(const T& v){
// 1.除0问题
// 2.数据映射关系打乱
if (_table.size() == 0 || 10 * _num / _table.size() >= 7){
size_t newsize = _table.size() == 0 ? 10 : _table.size() * 2;
/* vector<HashStruct> newtable;
newtable.resize(newsize);
for (size_t i = 0; i < _table; i++)
{
if (_table[i]._state == EXIST)
{}
}
*/
HashTable<K, T> newht;
newht._table.resize(newsize);
for (size_t i = 0; i < newht._table.size(); ++i){
newht._table[i]._state = EMPTY;
}
for (size_t i = 0; i < _table.size(); ++i){
if (_table[i]._state == EXIST){
newht.Insert(_table[i]._v);
}
}
_table.swap(newht._table);
}
/*
* 1. 线性探测
*
*/
//size_t index = v % _table.size();
//while (_table[index]._state == EXIST){
// if (_table[index]._v == v){
// return false;
// }
// ++index;
// if (index == _table.size())
// index = 0;
//}
//2. 二次探测
size_t start = v % _table.size();
size_t index = start;
size_t i = 1;
while (_table[index]._state == EXIST){
if (_table[index]._v == v){
return false;
}
index = start + i*i;
index %= _table.size();
++i;
}
_table[index]._v = v;
_table[index]._state = EXIST;
_num++;
return true;
}
HashStruct* Find(const K& k){
if (_table.size() == 0)
return nullptr;
size_t index = k % _table.size();
while (_table[index]._state != EMPTY){
if (_table[index]._v == k && _table[index]._state == EXIST){
return &_table[index];
}
++index;
if (index == _table.size()){
index = 0;
}
}
return nullptr;
}
bool Erase(const K& k){
HashStruct* ret = Find(k);
if (ret == nullptr){
return false;
}
else{
ret->_state = DELETE;
--_num;
return true;
}
}
private:
//线性存储所需的成员变量:
//HashStruct* _table;
//size_t _size;
//size_t _capacity;
vector<HashStruct> _table; //链式结构
size_t _num = 0; // 映射存储的数据个数
};
void TestHashTable(){
//HashTable<int, int> s;
//s.Insert(5);
//s.Insert(3);
//s.Insert(2);
//s.Insert(12);
//s.Insert(22);
//s.Insert(9);
//s.Insert(8);
//s.Insert(7);
HashTable<int, int> s;
s.Insert(2);
s.Insert(12);
s.Insert(22);
s.Insert(32);
}
}
2. 开散列【优】
概念
开散列法又叫==链地址法==(开链法
),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶(哈希桶),各个桶中的元素通过一个==单链表==链接起来,各链表的头结点存储在哈希表中。开散列中每个桶中放的都是发生哈希冲突的元素。
开散列的代码实现
namespace hashbucket{ //哈希桶
template<class T>
struct HashNode{
HashNode<T>* _next; //使用单向链表,正好符合哈希结构只有正向迭代器,无反向迭代器rbegin()...
T _v;
HashNode(const T& t)
:_v(t)
, _next(nullptr)
{}
};
template<class K, class T, class KeyOfValue, class HF>
class HashTable; //前置声明,防止编译发现未定义的类型而无法通过
template<class K, class T, class KeyOfValue, class HF>
struct __HTIterator{
typedef HashNode<T> Node;
typedef __HTIterator<K, T, KeyOfValue, HF> Self;
Node* _node;
HashTable<K, T, KeyOfValue, HF>* _pht;
__HTIterator(Node* node, HashTable<K, T, KeyOfValue, HF>* pht)
:_node(node)
, _pht(pht)
{}
T& operator*(){
return _node->_v;
}
T* operator->(){
return &(operator*());
}
// ++it
Self& operator++(){
if (_node->_next){
_node = _node->_next;
}
else{
KeyOfValue kov;
size_t index = _pht->HashFunc(kov(_node->_v), _pht->_table.size());
++index;
while (index < _pht->_table.size()){
if (_pht->_table[index]){
_node = _pht->_table[index];
break;
}
else{
++index;
}
}
// 所有桶走完了,置为nullptr表示end()的位置
if (index == _pht->_table.size()){
_node = nullptr;
}
}
return *this;
}
bool operator!= (const Self& s){
return _node != s._node;
}
};
template<class K, class T, class KeyOfValue, class HF>
class HashTable{
typedef HashNode<T> Node;
//friend struct __HTIterator<K, T, KeyOfValue, HF>;
template<class K, class T, class KeyOfValue, class HF>
friend struct __HTIterator;
public:
typedef __HTIterator<K, T, KeyOfValue, HF> iterator;
iterator begin(){
if (_num == 0){
return end();
}
for (size_t i = 0; i < _table.size(); ++i){
if (_table[i] != nullptr){
return iterator(_table[i], this);
}
}
return end();
}
iterator end(){
return iterator(nullptr, this);
}
pair<iterator, bool> Insert(const T& v){
KeyOfValue kov;
// 增容 load factor == 1
if (_table.size() == _num){
size_t newsize = _table.size() == 0 ? 10 : _table.size() * 2;
vector<Node*> newtable;
newtable.resize(newsize);
// 挪动旧表数据到新表计算新的位置
for (size_t i = 0; i < _table.size(); ++i){
Node* cur = _table[i];
while (cur){
Node* next = cur->_next;
size_t index = HashFunc(kov(cur->_v), newtable.size());
cur->_next = newtable[index];
newtable[index] = cur;
cur = next;
}
_table[i] = nullptr;
}
newtable.swap(_table);
}
size_t index = HashFunc(kov(v), _table.size());
Node* cur = _table[index];
while (cur){
if (kov(cur->_v) == kov(v)){
return make_pair(iterator(cur, this), false);
}
cur = cur->_next;
}
// 头插
Node* newnode = new Node(v);
newnode->_next = _table[index];
_table[index] = newnode;
++_num;
return make_pair(iterator(newnode, this), true);
}
iterator Find(const K& k){
KeyOfValue kov;
size_t index = HashFunc(k, _table.size());
Node* cur = _table[index];
while (cur){
if (kov(cur->_v) == k){
return iterator(cur, this);
}
cur = cur->_next;
}
return end();
}
bool Erase(const K& k){
KeyOfValue kov;
size_t index = HashFunc(k, _table.size());
Node* prev = nullptr;
Node* cur = _table[index];
while (cur){
if (kov(cur->_v) == k){
if (prev == nullptr){
_table[index] = cur->_next;
}
else{
prev->_next = cur->_next;
}
delete cur;
return true;
}
prev = cur;
cur = cur->_next;
}
}
size_t HashFunc(const K& k, size_t n){
HF hf;
return hf(k) % n;
}
private:
vector<Node*> _table; //桶式结构
size_t _num = 0;
};
}
开散列与闭散列比较:
应用链地址法处理溢出,需要增设链接指针,似乎增加了存储开销。事实上: 由于开地址法必须保持大量的空闲空间以确保搜索效率,如二次探查法要求装载因子a <= 0.7
,而表项所占空间又比指针大的多,所以使用链地址法反而比开地址法节省存储空间。