用hash表实现搜索(《编程珠玑》第九章)

来源:互联网 发布:淘宝介入后卖家输后果 编辑:程序博客网 时间:2024/05/05 03:41

用hash表实现搜索,时间复杂度是O(n),但是空间复杂度也是O(n),一般要比n大。优点是待搜索的数组不需要是排序好的。

此代码用链表来实现hash表的,用链表来解决冲突,我觉得这个解决冲突的办法相对高效些。

#include<iostream>#include<vector>#include<list>#include<algorithm>using namespace std;vector<list<int> > hashTable(1000);int hashCode(int n){<span style="white-space:pre"></span>return n%1000;}void insert(int n){hashTable[hashCode(n)].push_back(n);}bool find(int n){list<int>::iterator iter1=hashTable[hashCode(n)].begin();list<int>::iterator iter2=hashTable[hashCode(n)].end();while(iter1!=iter2){if(*iter1==n)return true;iter1++;}return false;}int main(){int A[1000];generate_n(A,1000,rand);for(int i=0;i<1000;i++)insert(A[i]);int n;while(cin>>n)cout<<find(n)<<endl;system("pause");    <span style="white-space:pre"></span>return 0;}


0 0
原创粉丝点击