搜索树与哈希表详解
目录
一、搜索树
1.1 概念
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值;
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值;
- 它的左右子树也分别为二叉搜索树。
如:
1.2 查找
若根节点不为空:
如果根节点==查找key 返回当前节点;
如果根节点 >查找key在其左子树查找;
如果根节点<查找key在其右子树查找;否则就是没有找到,返回null;
class Node{
public int val;
public Node left;
public Node right;
public Node(int val){
this.val = val;
}
}
//二叉搜索树
public class BinarySearchTree {
public Node root = null;
//查找
public Node search(int key){
Node cur = root;
while (cur != null){
if(cur.val == key){
return cur;
}else if(cur.val < key){
cur = cur.right;
}else{
cur = cur.left;
}
}
return null;
}
1.3 插入
- 用cur和parent来找到val需要存储的位置。
- parent.val 和val比较大小,确定是在左边还是在右边进行插入。
public boolean insert(int val) {
if(root == null) {
root = new Node(val);
return true;
}
Node cur = root;
Node parent = null;
while (cur != null) {
if(cur.val < val) {
parent = cur;
cur = cur.right;
}else if(cur.val == val) {
return false;//不能有相同的数据
}else {
parent = cur;
cur = cur.left;
}
}
Node node = new Node(val);
if(parent.val < val) {
parent.right = node;
}else {
parent.left = node;
}
return true;
}
1.4 删除
设待删除结点为 cur, 待删除结点的双亲结点为 parent;
- cur.left == null
-
cur 是 root,则 root = cur.right
-
cur 不是 root,cur 是 parent.left,则 parent.left = cur.right
-
cur 不是 root,cur 是 parent.right,则 parent.right = cur.right
-
cur.right == null
-
cur 是 root,则 root = cur.left
-
cur 不是 root,cur 是 parent.left,则 parent.left = cur.left
-
cur 不是 root,cur 是 parent.right,则 parent.right = cur.left
-
cur.left != null && cur.right != null
需要使用替换法进行删除: -
在cur的左树当中找最大值或者在cur的右树中找最小值
用它的值填补到被删除节点中,再来处理该结点的删除问题。
/**
* Created With IntelliJ IDEA
* Description:
* Users: yyyyy
* Date: 2022-02-19
* Time: 16:43
*
*/
class Node{
public int val;
public Node left;
public Node right;
public Node(int val){
this.val = val;
}
}
//二叉搜索树
public class BinarySearchTree {
public Node root = null;
//查找
public Node search(int key){
Node cur = root;
while (cur != null){
if(cur.val == key){
return cur;
}else if(cur.val < key){
cur = cur.right;
}else{
cur = cur.left;
}
}
return null;
}
//插入
public boolean insert(int val) {
if(root == null) {
root = new Node(val);
return true;
}
Node cur = root;
Node parent = null;
while (cur != null) {
if(cur.val < val) {
parent = cur;
cur = cur.right;
}else if(cur.val == val) {
return false;//不能有相同的数据
}else {
parent = cur;
cur = cur.left;
}
}
Node node = new Node(val);
if(parent.val < val) {
parent.right = node;
}else {
parent.left = node;
}
return true;
}
public void remove(int key){
Node cur = root;
Node parent = null;
while (cur != null){
if (cur.val == key){
removeNode(cur,parent);
break;
}else if(cur.val < key){
parent = cur;
cur = cur.right;
}else{
parent = cur;
cur = cur.left;
}
}
}
//cur代表要删除的节点
public void removeNode(Node cur,Node parent){
if (cur.left == null){
if(cur == root){
root = cur.right;
}else if(cur == parent.left){
parent.left = cur.right;
}else{
parent.right = cur.right;
}
}else if(cur.right == null){
if(cur == root){
root = cur.left;
}else if(cur == parent.left){
parent.left = cur.left;
}else {
parent.right = cur.left;
}
}else{//cur的左和右都不为空的情况
//找到cur的右子树的最小值然后进行替换
Node targetParent = cur;
Node target = cur.right;
while (target.left != null){
targetParent = target;
target = target.left;
}
cur.val = target.val;
if (target == targetParent.left){
targetParent.left = target.right;
}else {
targetParent.right = target.right;
}
}
}
public void inOrder(Node root){
if(root == null)return;
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
public static void main(String[] args) {
int[] arr = {2,45,19,12,3,8};
BinarySearchTree binarySearchTree = new BinarySearchTree();
for (int i = 0; i < arr.length; i++) {
binarySearchTree.insert(arr[i]);
}
binarySearchTree.inOrder(binarySearchTree.root);
System.out.println();
System.out.println("插入重复的数");
System.out.println(binarySearchTree.insert(2));
System.out.println("删除数据");
binarySearchTree.remove(2);
binarySearchTree.inOrder(binarySearchTree.root);
}
}
输出结果:
1.5 性能分析
插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度的函数,即结点越深,则比较次数越多。
但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:
最优情况下,二叉搜索树为完全二叉树,其平均比较次数为:log2N
;
最差情况下,二叉搜索树退化为单支树,其平均比较次数为:N/2
;
1.6 与java集类的关系
TreeMap
和 TreeSet
即 java 中利用搜索树实现的 Map 和 Set;实际上用的是红黑树,而红黑树是一棵近似平衡的二叉搜索树,即在二叉搜索树的基础之上 + 颜色以及红黑树性质验证。
二、哈希表
2.1 概念
顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O(log2N)
,搜索的效率取决于搜索过程中元素的比较次数。
理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。 如果构造一种存储结构,通过某种函数(hashFunc
)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。
不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。
2.2 冲突避免
由于我们哈希表底层数组的容量往往是小于实际要存储的关键字的数量的,这就导致一个问题,冲突的发生是必然的,但我们能做的应该是尽量的降低冲突率。
2.2.1哈希函数设计
引起哈希冲突的一个原因可能是:哈希函数设计不够合理。
哈希函数设计原则:
- 哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有m个地址时,其值域必须在0到m-1之间;
- 哈希函数计算出来的地址能均匀分布在整个空间中;
- 哈希函数应该比较简单;
常见哈希函数
-
直接定制法–(常用)
取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B
;
优点:简单、均匀;
缺点:需要事先知道关键字的分布情况;
使用场景:适合查找比较小且连续的情况;
面试题:字符串中第一个只出现一次字符;
class Solution {
public int firstUniqChar(String s) {
if(s == null){
return -1;
}
int[] arr = new int[26];
//统计每个字母出现的次数
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
arr[ch - 97]++ ;
}
//遍历字符串中得字母,如果该字母出现一次,则返回该字母的下标
for(int i = 0;i < s.length();i++){
char ch = s.charAt(i);
if(arr[(ch - 97)] == 1){
return i;
}
}
return -1;
}
}
-
除留余数法–(常用)
设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数:Hash(key) = key% p(p<=m)
,将关键码转换成哈希地址。
这样做会浪费地址空间。 -
平方取中法–(了解)
假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址; 再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址 平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况。 - 折叠法–(了解)
折叠法是将关键字从左到右分割成位数相等的几部分(最后一部分位数可以短些),然后将这几部分叠加求和,并按散列表表长,取后几位作为散列地址。
折叠法适合事先不需要知道关键字的分布,适合关键字位数比较多的情况。 - 随机数法–(了解)
选择一个随机函数,取关键字的随机函数值为它的哈希地址,即H(key) = random(key),其中random为随机数函数。通常应用于关键字长度不等时采用此法。 - 数学分析法–(了解)
设有n个d位数,每一位可能有r种不同的符号,这r种不同的符号在各位上出现的频率不一定相同,可能在某些位上分布比较均匀,每种符号出现的机会均等,在某些位上分布不均匀只有某几种符号经常出现。可根据散列表的大小,选择其中各种符号分布均匀的若干位作为散列地址。
例如:
假设要存储某家公司员工登记表,如果用手机号作为关键字,那么极有可能前7位都是相同的,那么我们可以选择后面的四位作为散列地址,如果这样的抽取工作还容易出现冲突,还可以对抽取出来的数字进行反转(如1234改成4321)、右环位移(如1234改成4123)、左环移位、前两数与后两数叠加(如1234改12+34=46)等方法。
数字分析法通常适合处理关键字位数比较大的情况,如果事先知道关键字的分布且关键字的若干位分布较均匀的情况。
注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突。
2.2.2 冲突避免-负载因子调节
负载因子和冲突率的关系图:
所以当冲突率达到一个无法忍受的程度时,我们需要通过降低负载因子来变相的降低冲突率。
已知哈希表中已有的关键字个数是不可变的,那我们能调整的就只有哈希表中的数组的大小。
2.3 冲突解决-闭散列
解决哈希冲突两种常见的方法是:闭散列和开散列。
闭散列:也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key存放到冲突位置中的“下一个” 空位置中去。
下一个空位置的寻找方法:
1. 线性探测
例如:数据集合{1,7,6,4,5,9};
哈希函数设置为:hash(key) = key % capacity
; capacity
为存储元素底层空间总的大小,这里capacity = 10
;
比如上面的场景,现在需要插入元素44,先通过哈希函数计算哈希地址,下标为4,因此44理论上应该插在该位置,但是该位置已经放了值为4的元素,即发生哈希冲突。
线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。
插入:
通过哈希函数获取待插入元素在哈希表中的位置,如果该位置中没有元素则直接插入新元素,如果该位置中有元素发生哈希冲突,使用线性探测找到下一个空位置,插入新元素。
缺点:会将冲突元素都放在一起。
采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他元素的搜索。比如删除元素4,如果直接删除掉,44查找起来可能会受影响。因此线性探测采用标记的伪删除法来删除一个元素。
2. 二次探测
线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就是挨着往后逐个去找,因此二次探测为了避免该问题,找下一个空位置的方法为:Hi = (H0 + i2 )% m, 或者:Hi= (H0 - i2)% m。式中:i代表第几次冲突,其中:i = 1,2,3…, 是通过散列函数Hash(x)对元素的关键码 key 进行计算得到的位置,m是表的大小。上表中如果要插入44,产生冲突,使用解决后的情况为:
研究表明:当表的长度为质数且表装载因子a不超过0.5时,新的表项一定能够插入,而且任何一个位置都不会被探查两次。因此只要表中有一半的空位置,就不会存在表满的问题。在搜索时可以不考虑表装满的情况,但在插入时必须确保表的装载因子a不超过0.5,如果超出必须考虑增容。
因此:闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。
2.4 冲突-解决-开散列/哈希桶
开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。
底层本质上来说就是数组+链表的形式。
从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素。
开散列,可以认为是把一个在大集合中的搜索问题转化为在小集合中做搜索了。
2.5 冲突严重时的解决方法
刚才我们提到了,哈希桶其实可以看作将大集合的搜索问题转化为小集合的搜索问题了,那如果冲突严重,就意味着小集合的搜索性能其实也时不佳的,这个时候我们就可以将这个所谓的小集合搜索问题继续进行转化,例如:
- 每个桶的背后是另一个哈希表
- 每个桶的背后是一棵搜索树
2.6 性能分析
虽然哈希表一直在和冲突做斗争,但在实际使用过程中,我们认为哈希表的冲突率是不高的,冲突个数是可控的,也就是每个桶中的链表的长度是一个常数,所以,通常意义下,我们认为哈希表的插入/删除/查找时间复杂度是O(1) 。
2.7 哈希表实现
import org.omg.CORBA.NO_IMPLEMENT;
public class HashBuck {
static class Node{
public int key;
public int val;
public Node next;
public Node (int key,int val){
this.key = key;
this.val = val;
}
}
public Node[] arr;
public int usedSize;
public static final double DEFAULT_LOADFACTOR = 0.75;
public HashBuck(){
this.arr = new Node[10];
}
/**
*
* put函数
* @param key
* @param val
*/
public void put(int key,int val){
//1.找到key所在的位置
int index = key % this.arr.length;
//遍历这个下标的链表,看是不是有相同的key,有,要更新val
Node cur = arr[index];
while (cur != null){
if(cur.key == key){
cur.val = val;
return;
}
cur = cur.next;
}
//没有key这个元素
//头插法插入这个元素
Node node = new Node(key,val);
node.next = arr[index];
arr[index] = node;
this.usedSize++;
//插入元素之后,检查当前散列的负载因子是否大于负载因子
if(loadFactor() > DEFAULT_LOADFACTOR){
//增加散列表长度
resize();
}
}
//计算负载因子
private double loadFactor() {
return usedSize * 1.0 / arr.length;
}
//如果扩容数组,增加散列表长度,那么数组里面每个列表的元素都要进行重新哈希
private void resize() {
//扩容至原来长度的2倍
Node[] newArray = new Node[arr.length * 2];
for (int i = 0; i < arr.length; i++) {
Node cur = arr[i];
//cur ! null 就遍历当前下标下面的链表
while (cur != null){
int index = cur.key % newArray.length;//获取新的下标
//把cur这个节点以头插或者尾插的形式插入到新的数组对应的下标
//这里选用的是头插法
Node curNext = cur.next;
cur.next = newArray[index];//先绑定后面
newArray[index] = cur;//绑定前面
cur = curNext;
}
}
arr = newArray;
}
/**
* 根据key获取val值
* @param key
* @return
*/
public int get(int key){
int index = key % this.arr.length;
Node cur = arr[index];
while (cur != null){
if(cur.key == key){
return cur.val;
}
cur = cur.next;
}
return -1;
}
public static void main(String[] args) {
HashBuck hashBuck = new HashBuck();
hashBuck.put(1,1);
hashBuck.put(12,12);
hashBuck.put(3,3);
hashBuck.put(6,6);
hashBuck.put(7,7);
hashBuck.put(2,2);
hashBuck.put(11,11);
hashBuck.put(8,8);
System.out.println(hashBuck.get(11));//11
}
}
当放入7个元素的时候,负载因子为:7/10 = 0.7 < 0.75,没有超过负载因子的大小,不进行扩容,则里面元素的运行情况如下:
这是采用头插法的方式放入的元素:
当usedSize = 8
时,负载因子为:8/10 = 0.8 > 0.75,超过了负载因子的大小,进行扩容,扩容后容量为20。
当 key和 value都为引用类型时:
要让person1
和person2
指向同一个人必须重写HashCode()
方法。
import javax.xml.soap.SAAJResult;
import java.util.Objects;
class Person{
public String id;
public Person(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(id, person.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Person{" +
"id='" + id + ''' +
'}';
}
}
public static void main(String[] args) {
//hashCode
//person1和person2为同一个人
Person person1 = new Person("13");
Person person2 = new Person("13");
System.out.println(person1.hashCode());
System.out.println(person2.hashCode());
}
}
通过HashCode()函数找到下标位置,通过equals()来看以这个下标的链表当中的key是否一样。
HashCode
一样,equals
不一定一样。
equals
一样, HashCode
一定一样。
import javax.xml.soap.SAAJResult;
import java.util.HashMap;
import java.util.Objects;
class Person{
public String id;
public Person(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(id, person.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Person{" +
"id='" + id + ''' +
'}';
}
}
public class HashBuck2<K,V> {
static class Node<K,V> {
public K key;
public V val;
public Node<K, V> next;
public Node(K key, V val) {
this.key = key;
this.val = val;
}
}
public Node<K,V>[] arr = (Node<K,V>[]) new Node[10];
public int usedSize;
public void put(K key,V val){
int hash = key.hashCode();
int index = hash % arr.length;
Node<K,V> cur = arr[index];
//遍历这个下标的链表,看是不是有相同的key,有,要更新val
while (cur != null){
if(cur.key.equals(key)){
cur.val = val;
return;
}
cur = cur.next;
}
//没有key这个元素
//头插法插入这个元素
Node<K,V> node = new Node<>(key,val);
node.next = arr[index];
arr[index] = node;
this.usedSize++;
}
public V get(K key){
int hash = key.hashCode();
int index = hash % arr.length;
Node<K,V> cur = arr[index];
while (cur != null){
if(cur.key.equals(key)){
return cur.val;
}
cur = cur.next;
}
return null;
}
public static void main(String[] args) {
Person person1 = new Person("13");
Person person2 = new Person("13");
HashBuck2<Person,String> hashBuck2 = new HashBuck2<>();
hashBuck2.put(person1,"he");
System.out.println(hashBuck2.get(person2));
}
}
2.8 和 java 类集的关系
-
HashMap
和HashSet
即 java 中利用哈希表实现的 Map 和 Set; - java 中使用的是哈希桶方式解决冲突的;
- java 会在冲突链表长度大于一定阈值后,将链表转变为搜索树(红黑树)
一般是链表长度大于8,数组长度超过64; - java 中计算哈希值实际上是调用的类的
hashCode
方法,进行 key 的相等性比较是调用 key 的equals
方法。所以如果要用自定义类作为HashMap
的 key 或者HashSet
的值,必须覆写hashCode
和equals
方法,而且要做到equals
相等的对象,hashCode
一定是一致的。
1.如果new HashMap(19)
,bucket
数组多大?
大于等于19&&最接近19的一个2次幂 —>32
2.HashMap
什么时候开辟bucket
数组占用内存?
第一次put的时候才会分配一个默认容量16
3.hashMap
何时扩容?
超过负载因子时扩容,是2倍扩容的。
4.当两个对象的hashcode
相同会发生什么?
冲突
5.如果两个键的hashcode
相同,你如何获取值对象?
遍历与
hashCode
值相等(equals)时相连的链表,直到相等(用equals判断是否相等)或者null
6.你了解重新调整HashMap
大小后存在什么问题吗?
需要重新哈希原来的元素到新的链表当中。
以上。