字符哈希
用来统计一个字符串中,每个字符的个数。
#include "util.h"
using namespace std;
int main(){
int char_map[128] = {0};
string str = "abcdefgaaxxy";
for (int i = 0; i < str.length(); ++i) {
char_map[str[i]]++;
}
for (int i = 0; i < 128; ++i) {
if (char_map[i] > 0){
printf("[%c][%d] : %d\n",i,i,char_map[i]);
}
}
return 0;
}
用hash表来排序整数
#include "util.h"
using namespace std;
int main(){
int random [10] = {999,1,444,7,20,9,1,3,7,7};
int hash_map[1000] ={0};
for (int i = 0; i < 10; ++i) {
hash_map[random[i]]++;
}
for (int i = 0; i < 1000; ++i) {
for (int j = 0; j < hash_map[i]; ++j) {
printf("%d\n",i);
}
}
return 0;
}
链地址法解决哈希冲突,构造哈希表
#include "util.h"
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x) : val(x),next(nullptr){}
};
int hash_func(int key, int table_len){
return key % table_len;
}
void insert(ListNode* hash_table[], ListNode* node,int table_len){
int hash_key = hash_func(node->val, table_len);
node->next = hash_table[hash_key];
hash_table[hash_key] = node;
}
bool search(ListNode* hash_table[],int value, int table_len){
int hash_key = hash_func(value,table_len);
ListNode* head = hash_table[hash_key];
while (head){
if (head->val == value){
return true;
}
head = head->next;
}
return false;
}
int main(){
const int TABLE_LEN = 11;
ListNode* hash_table[TABLE_LEN] = {nullptr};
vector<ListNode*> hash_node_vec;
int test[8] = {1,1,4,9,20,30,150,500};
for (int i = 0; i < 8; ++i) {
hash_node_vec.push_back(new ListNode(test[i]));
}
for (int i = 0; i < hash_node_vec.size(); ++i) {
insert(hash_table, hash_node_vec[i],TABLE_LEN);
}
printf("Hash table : \n");
for (int i = 0; i < TABLE_LEN; ++i) {
printf("[%d] : ",i);
ListNode* head = hash_table[i];
while (head){
printf("->%d",head->val);
head = head->next;
}
printf("\n");
}
printf("\n");
printf("Test search: \n");
for (int i = 0; i < 10; ++i) {
if(search(hash_table,i,TABLE_LEN)){
printf("%d is in the hash table.\n",i);
}
else{
printf("%d is not in the hash table.\n",i);
}
}
return 0;
}
hash_map和STL_map的区别
#include "util.h"
using namespace std;
int main(){
map<string, int> hash_map;
string str1 = "abc";
string str2 = "aaa";
string str3 = "xxxxx";
hash_map[str1] = 1;
hash_map[str2] = 2;
hash_map[str3] = 100;
if (hash_map.find(str1) != hash_map.end()){
printf("%s is in hash_map, value is %d\n",
str1.c_str(),hash_map[str1]);
}
for (auto it = hash_map.begin();it != hash_map.end();++it){
printf("hash_map[%s] = %d\n",it->first.c_str(),it->second);
}
return 0;
}
STL 的底层是红黑树,所以他的hashmap 是自然有序的,因为是STL的容器,所以它可以使用迭代器来遍历容器中的每一个数字。