散列的概念
目标和手段:
- 为了更快的查找-O(1)
- 拿空间换时间
散列:
- 键值对思想(key-value pair)
两个关键问题
1. 什么是好的散列函数?
- 快速计算
- 元素尽可能散开
2. 有哪些方法可以解决冲突 - 开放定址法
如果要坐的位置已有元素,则依次往后坐 - 分离链法
所有要坐该位置的元素都在该位置依次形成单链表 - 其他(公共溢出区等)
如果要坐的位置已有元素,则都存储在公共溢出区
散列的实现
C++实现
C++中STL的map和set底层都是使用红黑树实现,红黑树是一种近乎平衡的树,内部是一个排好序的结构。
如果我们有大量的数据,需要进行十分重负荷的查询操作,而对内部是不是排序不关心,这种情况下采用unordered_map和unordered_set。
#include <iostream>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> s;
unordered_map<int,int> m;
m[101]=33;
m[34]=45;
m.insert(pair<int,int>(23,89));
for(auto it=m.begin();it!=m.end();it++)
cout<<it->first<<" "<<it->second<<endl;
return 0;
}
//23 89
//34 45
//101 33
//
//Process returned 0 (0x0) execution time : 0.080 s
//Press any key to continue.
python实现
d = dict()
# also can init by "d={}"
d[100]=50
d[20]=30
d[10]='hello'
d[2]='world'
print(d)
print(2 in d)
print(-2 in d)
print('hello' in d)
'''
PS D:\C++_QJX> & C:/Users/QinJX/AppData/Local/Programs/Python/Python37/python.exe d:/Python_QJX/py_20191022_1.py
{100: 50, 20: 30, 10: 'hello', 2: 'world'}
True
False
False
'''