用PriorityQueue优先队列实现最小堆和最大堆
1.写法一:使用lambda写法来构建比较规则
1.最小堆:默认为最小堆
//默认为小根堆(看成升序排列)
Queue<Integer> minHeap =new PriorityQueue<Integer>()
2.最大堆:
//默认为小根堆(看成升序排列)
Queue<Integer> minHeap =new PriorityQueue<Integer>((a, b)->a-b); // 最小堆(升序)
Queue<Integer> maxHeap =new PriorityQueue<Integer>((a, b)->b-a); // 最大堆(降序)
2.写法二:比较器实现
Queue<Integer> minHeap=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
/**以下是对比较器升序、降序的理解.
*(1) 写成return o1.compareTo(o2) 或者 return o1-o2表示升序——最小堆
*(2) 写成return o2.compareTo(o1) 或者return o2-o1表示降序——最大堆
**/
//return o1.compareTo(o2);
return o1-o2;
}
});
3.泛型为Map,并且需要比较的是哈希表的值
使用写法一:
1.最小堆
PriorityQueue<Map.Entry<Integer,Integer>> minHeap=new PriorityQueue<>((e1, e2)-> e1.getValue()-e2.getValue());
2.最大堆
PriorityQueue<Map.Entry<Integer,Integer>> maxHeap=new PriorityQueue<>((e1, e2)-> e2.getValue()-e1.getValue());
使用写法二:
Queue<Map.Entry<Integer,Integer>> minHeap=new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
/**以下是对比较器升序、降序的理解.
*(1) 写成return o1.getValue().compareTo(o2.getValue()) 或者return o1.getValue()-o2.getValue()表示升序——最小堆
*(2) 写成return o2.getValue().compareTo(o1.getValue()) 或者return o2.getValue()-o1.getValue()表示降序——最大堆
**/
// return o1.getValue().compareTo(o2.getValue());
return o1.getValue()-o2.getValue();
}
});
如果默认使用最小堆则可以这样写,对哈希表的值进行比较:
// ——这种写法是默认使用最小堆,并设置比较的是哈希表中的值,即频率
Queue<Map.Entry<Integer,Integer>> minHeap=new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
Queue<Map.Entry<Integer,Integer>> minHeap=new PriorityQueue<>(Map.Entry.comparingByValue());
4.泛型为int[]
使用写法一
1.最小堆
Queue<int[]> minHeap=new PriorityQueue<>((p1,p2)->p1[0]-p2[0]+p1[1]-p2[1]);
2.最大堆
Queue<int[]> maxHeap=new PriorityQueue<>((p1,p2)->p2[0]-p1[0]+p2[1]-p2[1]);
使用写法二
Queue<int[]> minHeap=new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
/**以下是对比较器升序、降序的理解.
*(1) 写成return o1[0]-o2[0]+o1[1]-o2[1]表示升序——最小堆
*(2) 写成return o2[0]-o1[0]+o2[1]-o1[1]表示降序——最大堆
**/
return o1[0]-o2[0]+o1[1]-o2[1];
}
});