目录
1.二叉搜索树
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
- 它的左右子树也分别为二叉搜索树
public class BinarySearchTree {
static class TreeNode {
public int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode root;
/**
* 判断二叉搜索树中是否存在值为key的节点
* @param key
*/
public boolean search(int key) {
TreeNode cur = root;
if (cur == null) {
return false;
}
while (cur != null) {
if (cur.val > key) {
cur = cur.left;
} else if (cur.val < key) {
cur = cur.right;
} else {
return true;
}
}
return false;
}
/**
* 向二叉搜索树中插入元素
* @param val
*/
public void insert(int val) {
TreeNode node = new TreeNode(val);
TreeNode cur = root;
TreeNode parent = root;
if (cur == null) {
root = node;
return;
}
while (cur != null) {
if (cur.val > val) {
parent = cur;
cur = cur.left;
} else if (cur.val < val) {
parent = cur;
cur = cur.right;
} else {
//相同的节点不进行插入
return;
}
}
//cur为null,判断是p的左还是右
if(parent.val > val) {
parent.left = node;
}else {
parent.right = node;
}
}
/**
* 删除二叉搜索树的一个节点
* @param key
*/
public void remove(int key) {
TreeNode cur = root;
TreeNode parent = root;
if (cur == null) {
return;
}
while (cur != null) {
if (cur.val > key) {
parent = cur;
cur = cur.left;
} else if (cur.val < key) {
parent = cur;
cur = cur.right;
} else {
//开始删除节点
removeNode(parent,cur);
}
}
}
private void removeNode(TreeNode parent,TreeNode cur) {
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 {
TreeNode t = cur.right;
TreeNode tp = cur;
while (t.left != null) {
tp = t;
t = tp.left;
}
//开始删除
cur.val = t.val;
if (t == tp.left) {
tp.left = t.right;
} else {
tp.right = t.right;
}
}
}
}
2.搜索
(1)概念及场景
Map和set是一种专门用来进行搜索的容器或者数据结构,其搜索的效率与其具体的实例化子类有关
静态类型的查找,即一般不会对区间进行插入和删除操作了:
- 直接遍历,时间复杂度为O(N),元素如果比较多效率会非常慢
- 二分查找,时间复杂度为 ,但搜索前必须要求序列是有序的
动态查找,可能在查找时进行一些插入和删除的操作:
- Map和Set是 一种适合动态查找的集合容器。
动态查找在现实中的适用场景:
- 根据姓名查询考试成绩
- 通讯录,即根据姓名查询联系方式
- 不重复集合,即需要先搜索关键字是否已经在集合中
(2)模型
一般把搜索的数据称为关键字(Key),和关键字对应的称为值(Value),将其称之为Key-value的键值对,所以 模型会有两种:
- 纯 key 模型,比如:
有一个英文词典,快速查找一个单词是否在词典中
快速查找某个名字在不在通讯录中- Key-Value 模型,比如:
统计文件中每个单词出现的次数,统计结果是每个单词都有与其对应的次数:单词,单词出现的次数> 梁山好汉的江湖绰号:每个好汉都有自己的江湖绰号Map中存储的就是key-value的键值对,Set中只存储了Key。
3.Map
(1)特点
- Map是一个双列集合,一个元素包含两个值(K,V)
- Map集合中的元素,key和value的数据类型可以相同,也可以不同
- Map是一个接口类,该类没有继承自Collection,该类中存储的是结构的键值对,并且K一定是唯一的,不能重复,V可以重复
(2)常用方法
V get(Object key) | 返回 key 对应的 value |
V getOrDefault(Object key, V defaultValue) | 返回 key 对应的 value,key 不存在,返回默认值 |
V put(K key, V value) | 设置 key 对应的 value |
V remove(Object key) | 删除 key 对应的映射关系 |
Set keySet() | 返回所有 key 的不重复集合 |
Collection values() | 返回所有 value 的可重复集合 |
Set<Set.Entry<K,V>> entrySet() | 返回所有的 key-value 映射关系 |
boolean containsKey(Object key) | 判断是否包含 key |
boolean containsValue(Object value) | 判断是否包含 value |
- V put(K key, V value):把指定的键和值添加到Map集合中,返回值是V
如果要存储的键值对,key不重复返回值V是null
如果要存储的键值对,key重复返回值V是被替换的value值
Map<String,String> map = new TreeMap<>(); String val1 = map.put("孙悟空","齐天大圣1"); System.out.println(val1); String val2 = map.put("孙悟空","齐天大圣2"); System.out.println(val2); System.out.println(map);
- V remove(Object key):把指定键所对应的键值对元素,在Map集合中删除,返回被删除的元素的值。
如果key存在,返回被删除的值,如果key不存在,返回nullString ret1 = map.remove("孙悟空"); System.out.println(ret1); String ret2 = map.remove("孙悟空1"); System.out.println(ret2);
V get(Object key):根据指定的键 在Map集合中获取对应的值
如果key存在,返回对应的value值,如果key不存在,返回null
String val = map.get("孙悟空"); System.out.println(val);
- boolean containsKey( Object key):判断集合中是否包含指定的键,包含true,不包含false
boolean containsValue( Object Value):判断集合中是否包含指定的值,包含true,不包含false
boolean val3 = map.containsKey("孙悟空"); boolean val4 = map.containsValue("齐天大圣"); System.out.println(val3); System.out.println(val4);
(3)遍历Map集合的方式
- 通过键找值的方法
使用了setKey方法,将Map集合中的key值,存储到Set集合,用迭代器或foreach循环遍历Set集合来获取Map集合的每一个key,并使用get(key)方法来获取value值Map<String,String> map = new TreeMap<>(); map.put("孙悟空","齐天大圣"); map.put("六小龄童","齐天大圣"); Set<String> set = map.keySet(); System.out.println(set); Iterator<String> it = set.iterator(); while (it.hasNext()) { String key = it.next(); String val = map.get(key); System.out.println("key:" + key + " val:" + val); }
使用Entry对象遍历
Map.Entry<K,V>,在Map接口中有一个内部接口Entry(内部类)
作用:当集合一创建,就会在Map集合中创建一个Entry对象,用来记录键与值(键值对对象,键值的映射关系)
Set<Map.Entry<String,String>> entries = map.entrySet(); for (Map.Entry<String,String> entry: entries) { //System.out.println("key:" + entry.getKey() + " val:" + entry.getValue()); entry.setValue("弼马温"); System.out.println("key:" + entry.getKey() + " val:" + entry.getValue()); }
(4)注意事项
- Map是一个接口,不能直接实例化对象,如果要实例化对象只能实例化其实现类TreeMap或者HashMap
- Map中存放键值对的Key是唯一的,value是可以重复的
- TreeMap中插入键值对时,key不能为空,否则就会抛NullPointerException异常,value可以为空。但是HashMap的key和value都可以为空。
- Map中的Key可以全部分离出来,存储到Set中来进行访问(因为Key不能重复)。
public static void main(String[] args) { //Map中的Key可以全部分离出来,存储到Set中来进行访问(因为Key不能重复)。 Map<String,String> map = new TreeMap<>(); map.put("孙悟空","齐天大圣"); map.put("六小龄童","齐天大圣"); Set<String> set = map.keySet(); System.out.println(set); Iterator<String> it = set.iterator(); while (it.hasNext()) { String key = it.next(); System.out.println("key:" + key); } }
- Map中键值对的Key不能直接修改,value可以修改,如果要修改key,只能先将该key删除掉,然后再来进行 重新插入。
(5)Map的常用实现类
TreeMap和HashMap的区别
Map<String,String> map1 = new TreeMap<>(); Map<String,String> map2 = new HashMap<>();
4.Set
(1)特点
Set与Map主要的不同有两点:Set是继承自Collection的接口类,Set中只存储了Key。
(2)常用方法
(3)注意事项
- Set是继承自Collection的一个接口类
- Set中只存储了key,并且要求key一定要唯一
- TreeSet的底层是使用Map来实现的,其使用key与Object的一个默认对象作为键值对插入到Map中的
- Set最大的功能就是对集合中的元素进行去重
- 实现Set接口的常用类有TreeSet和HashSet,还有一个LinkedHashSet,LinkedHashSet是在HashSet的基础 上维护了一个双向链表来记录元素的插入次序。
- Set中的Key不能修改,如果要修改,先将原来的删除掉,然后再重新插入
- TreeSet中不能插入null的key,HashSet可以。
(4)Set的常用实现类
Set<String> s1 = new TreeSet<>(); Set<String> s2 = new HashSet<>();
5.哈希表
(1)前言
在我们之前学到的顺序结构和平衡树中,我们想查找一个元素必须经过关键码的多次比较才能找到,顺序结构的时间复杂度为O(N),平衡树的时间复杂度为树的高度,即O(logN),搜索的效率取决于搜索过程中元素的比较次数,这是因为元素的关键码与其存储的位置之间没有对应的关系;
那么我么想达到一种理想的状态就是可以不通过任何比较,一次就可以找到要搜索的元素,如果构造一种存储结构,通过某种函 数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快 找到该元素。
- 插入元素
根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放- 搜索元素
对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置取元素比较,若 关键码相等,则搜索成功该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)
例如:数据集合{1,7,6,4,5,9}; 哈希函数设置为:hash(key) = key % capacity; capacity为存储元素底层空间总的大小。
(2)哈希冲突
不同关键字通过相同哈希数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。
由于我们哈希表底层数组的容量往往是小于实际要存储的关键字的数量的,这就导致一 个问题,冲突的发生是必然的,但我们能做的应该是尽量的降低冲突率。
(3)哈希函数
引起哈希冲突的一个原因可能是:哈希函数设计不够合理。
直接定制法
取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B
优点:简单、均匀
缺点:需要事先知道关 键字的分布情况 使用场景:适合查找比较小且连续的情况
除留余数法
设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数: Hash(key) = key% p(p<=m) 将关键码转换成哈希地址
冲突-避免-负载因子调节
当冲突率达到一个无法忍受的程度时,我们需要通过降低负载因子来变相的降低冲突率。
已知哈希表中已有的关键字个数是不可变的,那我们能调整的就只有哈希表中的数组的大小。
(4)冲突解决
解决哈希冲突两种常见的方法是:闭散列和开散列
闭散列
闭散列:也叫开放地址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以 把key存放到冲突位置中的“下一个” 空位置中去。
- 线性探测
线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。
采用闭散列处理哈希冲突时,不能随便物理删除哈希表中已有的元素,若直接删除元素会影响其他 元素的搜索。比如删除元素4,如果直接删除掉,44查找起来可能会受影响。因此线性探测采用标 记的伪删除法来删除一个元素。- 二次探测
线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就是挨 着往后逐个去找,因此二次探测为了避免该问题,找下一个空位置的方法为:
研究表明:当表的长度为质数且表装载因子a不超过0.5时,新的表项一定能够插入,而且任何一个位置都不 会被探查两次。因此只要表中有一半的空位置,就不会存在表满的问题。在搜索时可以不考虑表装满的情 况,但在插入时必须确保表的装载因子a不超过0.5,如果超出必须考虑增容。
因此:闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。
开散列(哈希桶)
开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子 集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。
数组+链表组成
当数组长度>=64的时候并且链表长度>=8的时候这个链表就会变成红黑树
(5)模拟实现哈希桶
public class HashBuck {
static class Node {
public int key;
public int value;
public Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public Node[] array;
public int usedSize;
public double loadFactor = 0.75;//负载因子为0.75
public HashBuck () {
array = new Node[10];
}
public void put(int key,int value) {
int index = key % array.length;
Node cur = array[index]; //默认0,0,null
//1.遍历链表是否存在当前值 存在则更新
while (cur != null) {
if (cur.key == key) {
cur.value = value;
return;
}
cur = cur.next;
}
//2.插入该节点 头插
Node node = new Node(key,value);
node.next = array[index];
array[index] = node;
usedSize++;
//3.超出负载因子进行扩容
if (loadFacterCount() >= loadFactor) {
//扩容
resize();
}
}
public Double loadFacterCount() {
return usedSize*1.0 /array.length;
}
public void resize() {
//数组长度扩大为原数组的两倍
Node[] newArray = new Node[array.length*2];
//遍历链表
for (int i = 0; i < array.length; i++) {
Node cur = array[i];
while (cur != null) {
int newIndex = cur.key % newArray.length;
Node curN = cur.next;
cur.next = array[newIndex];
newArray[newIndex] = cur;
cur = curN;
}
}
}
public int get(int key) {
int index = key % array.length;
Node cur = array[index];
//1. 遍历当前链表 是否存在当前值
while (cur != null) {
if(cur.key == key) {
return cur.value;
}
cur = cur.next;
}
return -1;
}
}
public class HashBuck2<K,V> {
static class Node<K, V> {
public K key;
public V value;
public Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
public Node<K, V>[] array = (Node<K, V>[]) new Node[10];
public int usedSize;
public void put(K key, V value) {
int hash = key.hashCode();
int index = hash % array.length;
Node<K, V> cur = array[index];
//1.检查是否相同,相同更新
while (cur != null) {
if (cur.key.equals(key)) {
cur.value = value;
return;
}
cur = cur.next;
}
//2.不相同则头插
Node<K, V> node = new Node<K, V>(key, value);
node.next = array[index];
array[index] = node;
usedSize++;
}
public V get(K key) {
int hash = key.hashCode();
int index = hash % array.length;
Node<K, V> cur = array[index];
//1. 遍历当前链表 是否存在当前值
while (cur != null) {
if (cur.key.equals(key)) {
return cur.value;
}
cur = cur.next;
}
return null;
}
}