蓝桥杯——手写HashMap

  • hashMap
    hashMap就是散列表,能够以O(1)的速度快速实现查询,在C++中unordered_map就是hashMap。不过对于速度要求较高的场合,手写hashMap的速度大概是unordered_map的10倍
  • hash算法
//一般手写hash使用999997作为模数,这样能尽可能减少冲突
const long long int M=999997; 
vector<int> hashMap(M,-1);
//对x进行散列
long long int find(long long int x){
    
    
	//最常用散列算法
	long long int t=(x%M+M)%M;
	while(hashMap[t]!=-1&&hashMap[t]!=x){
    
    
		t++;
		if(t==M)	t=0;
	}
	//得到x在hash中的散列值
	return t;
} 

手写hash的速度取决于hash算法的好坏,hash算法冲突越少,那么速度越快

猜你喜欢

转载自blog.csdn.net/qq_33880925/article/details/129767987