赞
踩
预备知识:
1、最简单的哈希-----字符哈希
#include<stdio.h> #include<string> #include<stdlib.h> using namespace std; int main(){ int char_map[128] = {0};//ASCⅡ码从0-127,故用数组下标做映射,最大范围至128 string str="snaxjnjsxngdpq"; 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]);//将字符对应的ASCⅡ码及其个数打印出来 } system("pause"); return 0; }
2、哈希表排序整数
#include<stdio.h> #include<stdlib.h> using namespace std; int main(){ int random[10] = {3,456,78,43,124,789,908,78,3,124}; int hash_map[1000] = {0};//哈希表长度需要超过最大排序数 for(int i=0;i<10;i++){ hash_map[random[i]]++;//统计字符串中各个字符的数量 } for(int i=0;i<1000;i++){ //从小到大查询hash表中是否出现该数字,若出现则全部打出,打印结果就为排序后de for(int j = 0;j < hash_map[i];j++){ printf("%d\n",i); } } system("pause"); return 0; }
问题1:如何利用哈希表实现对任意字符的映射?
问题2:利用上述方式映射发生冲突怎么办?
用拉链法解决
#include<stdio.h> #include<stdlib.h> #include<vector> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; 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);//将插入节点的值转换为hash关键值 node->next = hash_table[hash_key];//利用头插法将新的节点插入对应哈希值位置 hash_table[hash_key] = node; } bool search(ListNode *hash_table[],int value,int table_len){//查找value值 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]={0}; vector<ListNode*> hash_node_vec; int test[8] = {14,17,404,109,9,6,7,81};//测试数组 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); } system("pause"); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。