#### 散列查找
- 核心思想
- 数据通过某一关键字或要素建立一个和存储地址相对应的映射关系,而建立这一映射过程则通过一个或多个特定的散列函数计算得到
- 特性
- 散列表用的是数组支持按照下标随机访问数据的特性,是对数组的一种扩展
- 再好的散列函数都无法避免散列冲突(将10个苹果放入9个抽屉中)
- 步骤
- 根据数据特性确定散列函数
- 对所有待查数据根据关键字通过散列函数和自身存储位置建立散列关系
- 提供关键字查询入口,通过散列函数对关键字获取对应数据
- 图解
- 示例
```java
package com.lyd.algorithm.find;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* 描述:散列查找
*

* - 根据数据特性确定散列函数 * - 对所有待查数据根据关键字通过散列函数和自身存储位置建立散列关系 * - 提供关键字查询入口,通过散列函数对关键字获取对应数据 *
* * @author lyd Date 2019/4/15 ProjectName:datastructure-algo Version: 1.0 */ @Slf4j public class HashSearch { /** * 散列表大小 */ private static final int HASH_SIZE = 8; /** * 通过数据构建一个散列表 */ private final Node[] tab = new Node[HASH_SIZE]; /** * 散列函数(这里我们用直接和散列表大小进行取模) * * @param key 散列的关键字 * @return 返回一个散列值 */ int hash(String key) { int hash; if (null == key) { hash = 0; } else { hash = key.hashCode() % HASH_SIZE; } return hash; } /** * 构建散列表 * * @param key 关键字 * @param value 数据 */ void buildHash(String key, int value) { int hash = hash(key); Node node = tab[hash(key)]; if (null == node) { node = new Node(hash, key, value, null); } else { node = new Node(hash, key, value, node); } tab[hash] = node; } /** * 散列查找 * * @param key 关键字 * @return 散列表中映射的数据 */ Object hashSearch(String key) { int hash = hash(key); Node node = tab[hash]; if (null == node) { return null; } Object value = null; do { if (hash == node.hash && node.key.equals(key)) { value = node.value; } node = node.next; } while (node != null && node.next != null); return value; } @AllArgsConstructor @NoArgsConstructor static class Node { private int hash; private Object key; private Object value; private Node next; } public static void main(String[] args) { HashSearch search = new HashSearch(); int[] source = new int[]{2, 2, 3, 13, 15, 13, 5, 6, 11, 16, 20, 17, 12, 5, 6, 11, 16, 11, 20, 17}; for (int i : source) { search.buildHash(i + "", i); } String target = "1"; Object result = search.hashSearch(target); log.info("call hashSearch result:{},target:{},source:{}", result, target, source); } } ```