大根堆和小根堆在排序和选择第K大的数中经常有用到。
在Java中是可以直接实现这两个中结构的,使用的优先队列
public class TIMU1 {
//小根堆
public PriorityQueue<Integer> minHead = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
//大根堆
public PriorityQueue<Integer> maxHead = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
public static void main(String[] args) {
TIMU1 ti = new TIMU1();
int[] arr = {2,9,4,7,3,6};
for(int i : arr){
ti.minHead.add(i);
ti.maxHead.add(i);
}
while(!ti.minHead.isEmpty() ){
System.out.print(ti.minHead.poll() + " ");
}
System.out.println();
while(!ti.maxHead.isEmpty()){
System.out.print(ti.maxHead.poll() + " ");
}
}
}