数据结构之哈希

一、unordered系列关联式容器

在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到O(log_2 N),即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个 unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是与其底层结构不同,unordered系列底层结构是哈希表。本文中只对unordered_map和unordered_set进行介绍, unordered_multimap和unordered_multiset可自行查看文档介绍。

#include <iostream>
#include <string>
#include <unordered_set>
#include <unordered_map>
using namespace std;

void test_unordered_set()
{
    unordered_set<int> us1;
    us1.insert(1);
    us1.insert(3);
    us1.insert(2);
    us1.insert(4);
    // for(auto e : us1)
    // {
    //     cout << e << " ";
    // }
    // cout << endl;
    unordered_set<int>::iterator it = us1.begin();
    while(it != us1.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;
}

void test_unordered_map()
{
    //统计水果出现的次数
    string arr[] = {"西瓜","西瓜","苹果","西瓜","苹果","苹果","西瓜","苹果","苹果","西瓜","苹果","香蕉","李子"};
    unordered_map<string,int> mp;
 
    //[]功能,1.插入key,value 2.修改value  3.插入+修改 4.查找
    for(auto& str : arr)
        ++mp[str];
 
    mp["left"];                  //1.插入
    mp["李子"] = 2;              //2.修改
    mp["梨"] = 10;               //3.插入 + 修改 
    cout << "西瓜:" << mp["西瓜"] << endl;  //4.查找(在是查找,不在是插入)
    unordered_map<string,int>::iterator it = mp.begin();
    while(it != mp.end())
    {
        cout << it->first << ":" << it->second <<endl;
        ++it;
    }
}

int main()
{
    test_unordered_map();
    return 0;
}

以毫秒计算插入、查找和删除性能。

基本使用与set和map并无太大差别,set和map是有序的,而unordered_set和unordered_map是无序的。但是在性能上,综合而言,unordered系列更好一点,尤其是查找方面,一骑绝尘。

二、哈希

1.提要

顺序结构以及平衡树 中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即 O(log_2 N),搜索的效率取决于搜索过程中元素的比较次数。

理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素

如果构造一种存储结构 ,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。

当向该结构中:

  • 插入元素

根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放

  • 搜索元素

对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置 取元素比较,若关键码相等,则搜索成功

2.概念

该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)

用该方法进行搜索不必进行多次关键码的比较,因此搜索的速度比较快

3.哈希冲突

对于两个数据元素的关键字k_i和 k_j(i != j),有k_i != k_j,但有:Hash(k_i) == Hash(k_j),即:不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。

把具有不同关键码而具有相同哈希地址的数据元素称为"同义词"。

4.哈希函数

引起哈希冲突的一个原因可能是:哈希函数设计不够合理。

哈希函数设计原则:

  • 哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值 域必须在0到m-1之间
  • 哈希函数计算出来的地址能均匀分布在整个空间中
  • 哈希函数应该比较简单

常见哈希函数

1. 直接定址法--(常用)

取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B

优点:简单、均匀

缺点:需要事先知道关键字的分布情况

使用场景:适合查找比较小且连续的情况

2. 除留余数法--(常用)

设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,

按照哈希函数:Hash(key) = key% p(p<=m),将关键码转换成哈希地址

5.哈希冲突解决

解决哈希冲突两种常见的方法是:闭散列开散列

1.闭散列

闭散列,也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key存放到冲突位置中的"下一个" 空位置中去。

闭散列本质是一个零和游戏,是一种博弈,占据别人的位置。

那么如何寻找下一个空位置?

hash = key % tablesize

1. 线性探测
  • 插入

依次找后面的位置进行存储。hash + i (i = 1 2 3...)

  • 删除

采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。

2. 二次探测
  • 插入

hash+i*i (i = 1 2 3...)

3.代码演示
namespace OpenAddressHash
{
    enum STATUS
    {
        EMPTY,
        EXIST,
        DELETE
    };

    template<class K, class V>
    struct HashData
    {
        pair<K, V> _kv;
        STATUS _state;
        HashData(pair<K, V> kv, STATUS state = EMPTY)
            : _kv(kv)
            , _state(state)
        {}

    };

    template<class K, class V>
    class HashTable
    {
    public:
        bool insert(const pair<K, V> kv)
        {
            if(find(kv.first))
                return false;
            //负载因子超过0.7就得扩容
            if(_table.size() == 0 || (_n * 10) / _table.size() >= 7 )
            {
                //繁琐,冗余
                //size_t newsize = _table.size() == 0 ? 10 : _table.size() * 2;
                // vector<HashData> newtable(newsize);
                // for(auto& data : _table)
                // {
                //     if(data._state == EXIST)
                //     {
                //         //重新计算元素在新表的位置
                //         size_t i = 1;
                //         size_t index = hashi;
                //         //寻找插入点
                //         while(newtable[index]._state == EXIST)
                //         {
                //             index = hashi + i;
                //             index %= newtable.size();
                //             ++i;
                //         }
                //         newtable[index]._kv = data._kv;
                //         newtable[index]._state = EXIST;
                //     }      
                // }
                // _table.swap(newtable);
                size_t newsize = _table.size() == 0 ? 10 : _table.size() * 2;
                HashTable<K, V> _ht;
                _ht._table.resize(newsize);
                for (auto &data : _table)
                    if(data._state == EXIST)
                        _ht.Insert(data._kv); //复用,优美,简洁
                _table.swap(_ht);
            }

            size_t hashi = kv.first % _table.size();

            //1.线性探测
            size_t i = 1;
            size_t index = hashi;
            //寻找插入点
            while(_table[index]._state == EXIST)
            {
                index = hashi + i;
                index %= _table.size();
                ++i;
            }
            _table[index]._kv = kv;
            _table[index]._state = EXIST;
            ++_n;

            return true;
        }
        HashData<K, V>* find(const K& key)
        {
            if(_table.size() == 0)
                return nullptr;
            size_t hashi = key / _table.size();
            size_t index = hashi;
            size_t i = 1;
            while(_table[index]._state != EMPTY)
            {
                if(_table[index]._state == EXIST
                &&  [index]._kv.first == key)
                {
                    return &_table[index];
                }
                index = hashi + i;
                index %= _table.size();
                ++i;

                //如果已经查找一圈,就说明表里全是存在+删除
                if(index == hashi)
                    break;
            }
            return nullptr;
        }

        bool erase(const K& key)
        {
            HashData<K, V> *ret = find(key);
            if(ret)
            {
                ret._state = DELETE;
                --_n;
                return true;
            }
            else
                return false;
        }

    private:
        vector<HashData<K, V>> _table;
        size_t _n; //哈希表中存在的元素个数
    };
}

2.开散列(重点)

开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地 址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。

1.代码演示
//哈希-开散列/哈希桶
namespace HashBucket
{
    template <class T>
    struct HashNode
    {
        T _data;
        HashNode<K, V>* _next;
        HashNode(const T& data)
            : _data(data)
            , _next(nullptr)
        {}
    };

    template<class K>
    struct HashFunc
    {
        K operator()(const K& key)
        {
            return key;
        }
    };

    //特化,如果是普通类型,走上面的,如果是string类型,走下面这个
    template<>
    struct HashFunc<string>
    {
       /* int operator()(const string& s)
        {
            size_t hashi = 0;
            for (auto ch : s)
            {
                hashi += ch;
            }
            return hashi;
        }*/
        //使用BKDRHash方法来计算字符串的哈希值
        size_t operator()(const string& s)
        {
            size_t hashi = 0;
            for (auto ch : s)
                hashi = hashi * 131 + ch;
            return hashi;
        }
    };

    template<class K, class T, class TransKey = HashFunc<K>>
    class HashTable
    {
        typedef HashNode<T> Node;
    public:
        ~HashTable()
        {
            for (auto& cur : _table)
            {
                if (cur)
                {
                    Node* node = cur;
                    cur = cur->_next;
                    delete node;
                    node = nullptr;
                }
                cur = nullptr;
            }
        }
    public:
        Node* find(const K& key)
        {
            TransKey tk;
            if (_table.size() == 0) return nullptr;
            size_t hashi = tk(key) % _table.size();
            Node* cur = _table[hashi];
            while(cur)
            {
                if (cur->_kv.first == key)
                    return cur;
                cur = cur->_next;
            }
            return nullptr;
        }

        bool erase(const K& key)
        {
            TransKey tk;
            if (!find(key))
                return false;
            assert(_table.size() != 0);
            size_t hashi = tk(key) % _table.size();
            Node* prev = nullptr;
            Node* cur = _table[hashi];
            while (cur)
            {
                if (cur->_kv.first == key)
                {
                    if (prev == nullptr)
                        _table[hashi] = cur->_next;
                    else 
                        prev->_next = cur->_next;          
                    delete cur;
                    cur = nullptr;
                    --_n;
                    return true;
                }
                else
                {
                    prev = cur;
                    cur = cur->_next;
                }
            }
            return false;
        }

        bool insert(const T& data)
        {
            TransKey tk;
            if (find(data))
                return false;
            //扩容
            if (_n == _table.size())
            {
                int newsize = _table.size() == 0 ? 10 : _table.size() * 2;
                vector<Node*> newtable(newsize);
                for (auto& cur : _table)
                {
                    while (cur)
                    {
                        size_t hashi = tk(cur->_data) % newtable.size();
                        Node* next = cur->_next;
                        cur->_next = newtable[hashi];
                        newtable[hashi] = cur;
                        cur = next;
                    }
                }
                _table.swap(newtable);
            }
            //插入
            size_t hashi = tk(data) % _table.size();
            Node* newnode = new Node(data);
            newnode->_next = _table[hashi];
            _table[hashi] = newnode;
            ++_n;
            return true;
        }

        //打印
        void Printlist()
        {
            int i = -1;
            for (auto cur : _table)
            {
                ++i;
                if (cur == nullptr)
                    continue;
                cout << "_table[" << i << "]:";
                while (cur)
                {
                    cout << cur->_data << "-> ";
                    cur = cur->_next;
                }
                cout << endl;
            }
        }

        void Print()
        {
            for (auto cur : _table)
            {
                if (cur == nullptr)
                    continue;
                cout << cur->_data << endl;
            }
        }

    private:
        vector<Node*> _table; //指针数组
        size_t _n = 0;
    };

三、哈希应用

1.位图

所谓位图,就是用每一位来存放某种状态,适用于海量数据,数据无重复的场景。通常是用 来判断某个数据存不存在的。

1.位图的应用

  1. 快速查找某个数据是否在一个集合中
  2. 排序 + 去重
  3. 求两个集合的交集、并集等
  4. 操作系统中磁盘块标记

2.代码演示

#pragma once
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;

template<size_t N>
class bitset
{
public:
	bitset()
	{
		_bits.resize(N / 8 + 1, 0);
	}

	void set(size_t x)
	{
		size_t i = x / 8;
		size_t j = x % 8;
		_bits[i] |= (1 << j);
	}

	void reset(size_t x)
	{
		size_t i = x / 8;
		size_t j = x % 8;
		_bits[i] &= ~(1 << j);
	}

	bool test(size_t x)
	{
		size_t i = x / 8;
		size_t j = x % 8;
		return _bits[i] & (1 << j);
	}
private:
	vector<char> _bits;
};


//判断元素出现的次数,例如两个文件的数据元素交集
template<size_t N>
class doubleBitset
{
public:
	void set(size_t x)
	{
		// 00 - 01
		if (_bt1.test(x) == false
			&& _bt2.test(x) == false)
			_bt2.set(x);
		// 01 - 10
		else if (_bt1.test(x) == false
			&& _bt2.test(x) == true)
		{
			_bt1.set(x);
			_bt2.reset(x);
		}
		// 10 -	
	}
	void Print()
	{
		for (size_t i = 0; i < N; ++i)
		{
			if (_bt2.test(i))
				cout << i << endl;
		}
	}
private:
	bitset<N> _bt1;
	bitset<N> _bt2;
};

void test_doubleBitset()
{
	int arr[] = { 11 ,2 ,3,8,11,6,3 };
	doubleBitset<100> dbt1;
	for (auto i : arr)
		dbt1.set(i);
	dbt1.Print();

}

3.优缺点

优点:1.速度快 2.省空间

缺点:1.只能映射整形

2、布隆过滤器

1.布隆过滤器提出

我们在使用新闻客户端看新闻时,它会给我们不停地推荐新的内容,它每次推荐时要去重,去掉 那些已经看过的内容。问题来了,新闻客户端推荐系统如何实现推送去重的? 用服务器记录了用 户看过的所有历史记录,当推荐系统推荐新闻时会从每个用户的历史记录里进行筛选,过滤掉那 些已经存在的记录。 如何快速查找呢?

  1. 用哈希表存储用户记录,缺点:浪费空间
  2. 用位图存储用户记录,缺点:位图一般只能处理整形,如果内容编号是字符串,就无法处理 了。
  3. 将哈希与位图结合,即布隆过滤器

2.布隆过滤器概念

布隆过滤器是由布隆(Burton Howard Bloom)在1970年提出的 一种紧凑型的、比较巧妙的概率型数据结构 ,特点是高效地插入和查询,可以用来告诉你 "某样东西一定不存在或者可能存 在" ,它是用多个哈希函数,将一个数据映射到位图结构中。此种方式不仅可以提升查询效率 ,也 可以节省大量的内存空间

3.性质

布隆过滤器用于判断不在是准确的,判断在是不准确的

4.应用场景

1.能容忍误判的场景,例如:快速注册昵称是否被使用过。

假设 k == 3, m = 4.3n。

注:布隆过滤器不能直接支持删除工作,因为在删除一个元素时,可能会影响其他元素。

5.简易实现代码

/// @brief BKDR Hash Function  
/// @detail 本 算法由于在Brian Kernighan与Dennis Ritchie的《The C Programming Language》一书被展示而得名,
/// 是一种简单快捷的hash算法,也是Java目前采用的字符串的Hash算法(累乘因子为31)。
struct BKDRHash
{
	size_t operator()(const string& str)
	{
		register size_t hash = 0;
		for (auto& ch : str)
		{
			hash = 131 * hash + ch;
			//hash = (size_t)ch + (hash << 6) + (hash << 16) - hash;  
		}
		return hash;
	}
};

/// @brief AP Hash Function  
/// @detail 由Arash Partow发明的一种hash算法。  
struct APHash
{
	size_t operator()(const string& str)
	{
		register size_t hash = 0;
		
		for (long i = 0; /*ch = (size_t)(*str)++*/ i < str.size(); i++)
		{
			size_t ch = str[i];
			if ((i & 1) == 0)
			{
				hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
			}
			else
			{
				hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
			}
		}
		return hash;
	}
};

/// @brief DJB Hash Function  
/// @detail 由Daniel J. Bernstein教授发明的一种hash算法。  
struct DJBHash
{
	size_t operator()(const string& str)
	{
		if (str.size() == 0)   // 这是由本人添加,以保证空字符串返回哈希值0  
			return 0;
		register size_t hash = 5381;
		for (auto& ch : str)
		{
			hash += (hash << 5) + ch;
		}
		return hash;
	}
};

//哈希函数个数,代表一个值映射几个位,哈希函数越多,误判率越低
//但是哈希函数过多,平均消耗的空间越多。
template<
	size_t N,class K = string,
	class Hash1 = BKDRHash,
	class Hash2 = APHash,
	class Hash3 = DJBHash
>
class BloomFilter
{
public:
	void set(const K& key)
	{
		size_t len = N * _X;
		size_t hash1 = Hash1()(key) % len;
		_bs.set(hash1);

		size_t hash2 = Hash2()(key) % len;
		_bs.set(hash2);

		size_t hash3 = Hash3()(key) % len;
		_bs.set(hash3);

		cout << hash1 << " " << hash2 << " " << hash3 << endl << endl;
	}

	void test(const K& key)
	{
		size_t len = N * _X;
		size_t hash1 = Hash1()(key) % len;
		if (!_bs.test(hash1))
			return false;

		size_t hash2 = Hash2()(key) % len;
		if (!_bs.test(hash2))
			return false;

		size_t hash3 = Hash3()(key) % len;
		if (!_bs.test(hash3))
			return false;

		//在  --不准确的,存在误判
		//不在 --准确

		return true;
	}
private:
	static const size_t _X = 4;
	bitset<N*_X> _bs;
};

四、海量数据

1.哈希切割

相关推荐
Kalika0-039 分钟前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
代码雕刻家1 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
sp_fyf_20241 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-02
人工智能·神经网络·算法·计算机视觉·语言模型·自然语言处理·数据挖掘
小字节,大梦想2 小时前
【C++】二叉搜索树
数据结构·c++
我是哈哈hh3 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
Tisfy3 小时前
LeetCode 2187.完成旅途的最少时间:二分查找
算法·leetcode·二分查找·题解·二分
Mephisto.java3 小时前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
robin_suli3 小时前
滑动窗口->dd爱框框
算法
丶Darling.3 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo5203 小时前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法