需求场景
散列表一种经典的查找的算法,应用于在海量信息中进行高效检索。
简单需求
假设我们需要把10000000个字符串对象存放在数组中,使用什么存放策略能够快速定位某一个字符串的的数组位置,从而实现快速查找的效果?
暴力搜索
根据原始顺序存放,查找时遍历整个数组进行对比,返回匹配对象的下标
这样的查找方式,最好的情况是第一次查询时就命中,最坏的情况时查询到数组最后的位置才能找到元素。如果数据量非常大,将会占用很长时间。时间复杂度O(N)
代码实现如下:
public class ViolentSerch {
private int capcity;
private String[] strs;
public ViolentSerch() {
this.capcity = 20000000;
this.strs = new String[capcity];
for (int i = 0; i < capcity/2; i++) {
strs[i] = "str" + i;
}
}
public int getIndex(String str) {
for (int i = 0; i < strs.length; i++) {
if (strs[i].