B树
m阶B树的性质
搜索
添加
删除
B的上溢和下溢的解决方法是必须要学会的
四阶B树
上述练习可以很好地帮你巩固B树的知识,为红黑树的学习打下基础。
红黑树
红黑树的五条性质是非常重要的
红黑树与四阶B树的等价变换
几个重要概念
添加
添加的12种情况
此处grand向上合并看作向上层加新节点,需要重新判断属于12种添加中的哪种类型,重新进行修复
删除
删除BLACK叶子节点
1、想象B树的下溢处理,第一种情况是兄弟节点为黑色,且有红色子节点
2、第二种情况是兄弟节点为黑色,且没有红色子节点
3、第三种情况是兄弟节点为红色,且没有红色子节点
红黑树的平衡
平均时间复杂度
AVL树与红黑树的对比
集合
刷道leetcode
提交的答案
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for(int num: nums1)
set1.add(num);
for(int num: nums2)
set2.add(num);
return getIntersection(set1,set2);
}
public int[] getIntersection(Set<Integer> set1, Set<Integer> set2){
Set<Integer> intersection = new HashSet<Integer>();
if(set1.size() > set2.size()){
for(int num: set2){
if(set1.contains(num))
intersection.add(num);
}
}
else{
for(int num: set1){
if(set2.contains(num))
intersection.add(num);
}
}
int[] intersectionlist = new int[intersection.size()];
int index = 0;
for(int num: intersection){
intersectionlist[index++] = num;
}
return intersectionlist;
}
}
由于HashSet查找的时间复杂度为O(1),所以该解法的时间复杂度仅为O(两个数组长度之和)。
映射
使用AVL树、红黑树来实现Map,则为TreeMap
哈希表
装填因子
TreeMap和HashMap对比
二叉堆
以下以大顶堆为例,讲解添加、删除、建堆
添加
下图中的80为添加的节点
删除
批量建堆
方法1:
方法2:
效率对比
显然自下而上的下滤更加优秀,因为它是最少的节点在做最长长度的过滤
TopK问题
因为建的堆大小保持为k,每个数跟堆顶比较,并按情况进行更换,同时下滤,时间复杂度为O(logk)。总的时间复杂度为O(nlogk)。
堆排序比一般的排序算法要优秀,O(nlogk)< O(nlogn)。
优先级队列
优先级队列的底层实现可以用二叉堆