整数散列&字符串散列
前言
什么是散列?
用一句话概括就是 散列:将元素通过一个函数转换为整数,使得该整数可以尽量唯一地代表这个元素 。其中把这个函数称为散列函数H,如果元素在转换前为key,转换后就是H(key)。
本文将通过代码及注释展示简单的整数散列和字符串散列。
整数散列
#include
using namespace std;
//整数散列
//求M个欲查询的整数中每个数在N个数中出现的次数
//时间复杂度O(N + M)
const int K = 100001;
int hashTable[K] = {0};
int main(){
int N, M, X;
cin>>N>>M;
for(int i = 0; i < N; i++){//记录N个数中X出现次数
cin>>X;
hashTable[X]++;
}
cout<>X;
cout<
运行结果如图
字符串散列
#include
using namespace std;
//字符串散列
//给出N个恰好由三个大写字母组成的字符串,再给出M个查询字符串
const int k = 100;
char S[k][3], temp[3];
int hashTable[26*26*26+1];
int hashFunc(char S[], int len){// hash 函数,将字符串S转换为整数
int id = 0;
for(int i = 0; i < len; i++){
id = id*26 + (S[i] - 'A');
}
return id;
}
int main(){
int m, n;
cin>>n>>m;
for(int i = 0; i < n; i++){
cin>>S[i];
int id = hashFunc(S[i] , 3);
hashTable[id]++;
}
cout<>temp;
int id = hashFunc(temp , 3);
cout<
运行结果如图
附:
散列的详细概念请访问:散列的基本概念 博主:Shine__Wong
如有错误,欢迎在评论区指正