8-1 什麼是優先隊列
樹的不同結構,很靈活。例如之後的樹的幾個例子:堆,線段樹,字典樹,並查集。
首先我們來看堆
優先隊列的例子
- 計算機的操作系統,動態選擇優先級最高的任務執行。
我們使用堆實現優先隊列。
8-2 堆的基礎表示
- 二叉堆是一個完全二叉樹(結點按順序存放,所以我們可以使用數組來表示完全二叉樹)
- 二叉堆堆中某個結點的值總是不大於其父節點的值,最大堆
- 用數組存儲二叉堆
注意下標起始的影響
在這裏,我們使用一個從0開始的數組表示的二叉堆
public class MaxHeap <E extends Comparable<E>> {
private Array<E> data;
public MaxHeap(int capacity){
data = new Array<>(capacity);
}
public MaxHeap(){
data = new Array<>();
}
//返回堆中的元素個數
public int size(){
return data.getSize();
}
//返回一個布爾值,表示堆中是否爲空
public boolean isEmpty(){
return data.isEmpty();
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的父親節點的索引
private int parent(int index){
if (index == 0)
throw new IllegalArgumentException("index-0 doesn't hava parent");
return (index-1)/2;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的左孩子節點的索引
private int leftChild(int index){
return index * 2 + 1;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的右孩子節點的索引
private int rightChild(int index){
return index * 2 + 2;
}
}
8-3 向堆中添加元素和Sift Up
//向堆中添加元素
public void add(E e){
data.addLast(e);
siftUp(data.getSize()-1);
}
private void siftUp(int k){
while (k>0 && data.get(parent(k)).compareTo(data.get(k))<0){
data.swap(k,parent(k));
k = parent(k);
}
}
注意,要在Array裏添加swap方法
如下
public void swap(int i, int j){
if(i < 0 || i >= size || j < 0 || j >= size)
throw new IllegalArgumentException("Index is illegal.");
E t = data[i];
data[i] = data[j];
data[j] = t;
}
8-4 從堆中取出元素和Sift Down
// 取出堆中最大元素
public E extractMax(){
E ret = findMax();
data.swap(0, data.getSize() - 1);
data.removeLast();
siftDown(0);
return ret;
}
private void siftDown(int k){
while(leftChild(k) < data.getSize()){
int j = leftChild(k); // 在此輪循環中,data[k]和data[j]交換位置
if( j + 1 < data.getSize() &&
data.get(j + 1).compareTo(data.get(j)) > 0 )
j ++;
// data[j] 是 leftChild 和 rightChild 中的最大值
if(data.get(k).compareTo(data.get(j)) >= 0 )
break;
data.swap(k, j);
k = j;
}
}
8-5 Heapify 和 Replace
//取出堆中的最大元素,並且替換成元素e
public E replace(E e){
E ret = findMax();
data.set(0,e);
siftDown(0);
return ret;
}
//寫成一個構造函數
public MaxHeap(E[] arr){
data = new Array<>(arr);
for (int i = parent(arr.length-1);i>=0;i--)
siftDown(i);
}
比較測試使用heapify的方式創建堆和將數組中的元素逐個添加到空堆中的性能差異
import java.util.Random;
public class Main {
private static double testHeap(Integer[] testData,boolean isHeapify){
long startTime = System.nanoTime();
MaxHeap<Integer> maxHeap;
if (isHeapify)
maxHeap = new MaxHeap<>(testData);
else{
maxHeap = new MaxHeap<>();
for (int num:testData)
maxHeap.add(num);
}
int[] arr = new int[testData.length];
for (int i=0;i<testData.length;i++)
arr[i] = maxHeap.extractMax();
for (int i=1;i<testData.length;i++)
if (arr[i-1]<arr[i])
throw new IllegalArgumentException("Error");
System.out.println("Test MaxHeap completed");
long endTime = System.nanoTime();
return (endTime - startTime)/1000000000.0;
}
public static void main(String[] args) {
int n = 1000000;
Random random = new Random();
Integer[] testData = new Integer[n];
for (int i=0;i<n;i++)
testData[i] = random.nextInt(Integer.MAX_VALUE);
double time1 = testHeap(testData,false);
System.out.println("Without heapify:"+time1+" s");
double time2 = testHeap(testData,true);
System.out.println("Without heapify:"+time2+" s");
}
}
對於百萬級的數據量
Heapify的複雜度更低。
8-6 基於堆的優先隊列
由於優先隊列要排優先級,所以必須具有可比較性。
public class PriorityQueue<E extends Comparable<E>> implements Queue<E> {
private MaxHeap<E> maxHeap;
public PriorityQueue(){
maxHeap = new MaxHeap<>();
}
@Override
public int getSize(){
return maxHeap.size();
}
@Override
public boolean isEmpty(){
return maxHeap.isEmpty();
}
@Override
public E getFront(){
return maxHeap.findMax();
}
@Override
public void enqueue(E e){
maxHeap.add(e);
}
@Override
public E dequeue(){
return maxHe
ap.extractMax();
}
}
8-7 Leetcode上優先隊列相關問題
首先我們使用自己定義的PriorityQueue來解決這個問題
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
class Solution {
private class Freq implements Comparable<Freq>{
public int e,freq;
public Freq(int e,int freq){
this.e = e;
this.freq = freq;
}
@Override
//注意這裏應該使用最小堆我們用的是最大堆
//那麼這裏的這個優先級比較的規則應該是怎麼定義的?
public int compareTo(Freq another){
if (this.freq < another.freq)
return 1;
else if (this.freq>another.freq)
return -1;
else
return 0;
}
}
public List<Integer> topKFrequent(int[] nums, int k) {
//首先我們對每個數統計頻次
TreeMap<Integer,Integer> map = new TreeMap<>();
for (int num:nums){
if (map.containsKey(num))
map.put(num,map.get(num)+1);
else
map.put(num,1);
}
//構造優先隊列,找出前K個元素
PriorityQueue<Freq> pq = new PriorityQueue<Freq>();
for (int key:map.keySet()){
if (pq.getSize()<k)
pq.enqueue(new Freq(key,map.get(key)));
else if(map.get(key)>pq.getFront().freq){
pq.dequeue();
pq.enqueue(new Freq(key,map.get(key)));
}
}
//存儲答案
LinkedList<Integer> res = new LinkedList<>();
while (!pq.isEmpty())
res.add(pq.dequeue().e);
return res;
}
private static void printList(List<Integer> nums){
for (Integer num: nums)
System.out.println(num+" ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1,1,1,2,2,3};
int k = 2;
printList((new Solution()).topKFrequent(nums,k));
}
}
8-8 Java中的PriorityQueue
Java中的PriorityQueue和我們自己實現的不太一樣,我們這節來看看
首先我們使用Java庫中的PriorityQueue來解決上節的leetcode問題
- java的PriorityQueue內容默認是一個最小堆
- 沒有getSize()方法,直接是pq.size()
- dequeue對應pq.remove(),enqueue對應pq.add(new Freq(key,map.get(key))),getFront對應pq.peek()
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.PriorityQueue
//我們使用Java庫中的PriorityQueue來解決上節的leetcode問題
class Solution2 {
private class Freq implements Comparable<Freq>{
public int e,freq;
public Freq(int e,int freq){
this.e = e;
this.freq = freq;
}
@Override
//注意這裏的改變,java維護的是最小堆
public int compareTo(Freq another){
if (this.freq > another.freq)
return 1;
else if (this.freq<another.freq)
return -1;
else
return 0;
}
}
public List<Integer> topKFrequent(int[] nums, int k) {
//首先我們對每個數統計頻次
TreeMap<Integer,Integer> map = new TreeMap<>();
for (int num:nums){
if (map.containsKey(num))
map.put(num,map.get(num)+1);
else
map.put(num,1);
}
//構造優先隊列,找出前K個元素
PriorityQueue<Freq> pq = new PriorityQueue<Freq>();
for (int key:map.keySet()){
if (pq.size()<k)
pq.add(new Freq(key,map.get(key)));
else if(map.get(key)>pq.peek().freq){
pq.remove();
pq.add(new Freq(key,map.get(key)));
}
}
//存儲答案
LinkedList<Integer> res = new LinkedList<>();
while (!pq.isEmpty())
res.add(pq.remove().e);
return res;
}
private static void printList(List<Integer> nums){
for (Integer num: nums)
System.out.println(num+" ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1,1,1,2,2,3};
int k = 2;
printList((new Solution()).topKFrequent(nums,k));
}
}
根據我們的需要,如何改變java標準庫中相應類的比較規則。
java的解決方法:設置一個新的類,比較器,實現的是Comprarator接口
只需要覆蓋一個方法Compare,同時傳入的是兩個參數。
import java.util.*;
import java.util.PriorityQueue;
//我們使用Java庫中的PriorityQueue來解決上節的leetcode問題
class Solution3 {
private class Freq{
public int e,freq;
public Freq(int e,int freq){
this.e = e;
this.freq = freq;
}
}
private class FreqComparator implements Comparator<Freq>{
@Override
public int compare(Freq a,Freq b){
return a.freq - b.freq;
}
}
public List<Integer> topKFrequent(int[] nums, int k) {
//首先我們對每個數統計頻次
TreeMap<Integer,Integer> map = new TreeMap<>();
for (int num:nums){
if (map.containsKey(num))
map.put(num,map.get(num)+1);
else
map.put(num,1);
}
//構造優先隊列,找出前K個元素
PriorityQueue<Freq> pq = new PriorityQueue<>(new FreqComparator());
for (int key:map.keySet()){
if (pq.size()<k)
pq.add(new Freq(key,map.get(key)));
else if(map.get(key)>pq.peek().freq){
pq.remove();
pq.add(new Freq(key,map.get(key)));
}
}
//存儲答案
LinkedList<Integer> res = new LinkedList<>();
while (!pq.isEmpty())
res.add(pq.remove().e);
return res;
}
private static void printList(List<Integer> nums){
for (Integer num: nums)
System.out.println(num+" ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1,1,1,2,2,3};
int k = 2;
printList((new Solution()).topKFrequent(nums,k));
}
}
例如,使用上面這種方法,如果優先隊列裏傳的就是字符串,你想有一個自定義的字符串比較規則,此時你不能修改java內部的字符串定義方法,那麼可以在外面設置一個字符串的比較規則,傳給java的PriorityQueue就好了。
使用匿名類,具有變量捕獲capture的能力
import java.util.*;
import java.util.PriorityQueue;
public class Solution4 {
private class Freq{
public int e, freq;
public Freq(int e, int freq){
this.e = e;
this.freq = freq;
}
}
public List<Integer> topKFrequent(int[] nums, int k) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int num: nums){
if(map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}
PriorityQueue<Freq> pq = new PriorityQueue<>(new Comparator<Freq>() {
@Override
public int compare(Freq a, Freq b) {
return a.freq - b.freq;
}
});
for(int key: map.keySet()){
if(pq.size() < k)
pq.add(new Freq(key, map.get(key)));
else if(map.get(key) > pq.peek().freq){
pq.remove();
pq.add(new Freq(key, map.get(key)));
}
}
LinkedList<Integer> res = new LinkedList<>();
while(!pq.isEmpty())
res.add(pq.remove().e);
return res;
}
private static void printList(List<Integer> nums){
for(Integer num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
printList((new Solution()).topKFrequent(nums, k));
}
}
import java.util.*;
import java.util.PriorityQueue;
public class Solution5 {
public List<Integer> topKFrequent(int[] nums, int k) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int num: nums){
if(map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
for(int key: map.keySet()){
if(pq.size() < k)
pq.add(key);
else if(map.get(key) > map.get(pq.peek())){
pq.remove();
pq.add(key);
}
}
LinkedList<Integer> res = new LinkedList<>();
while(!pq.isEmpty())
res.add(pq.remove());
return res;
}
private static void printList(List<Integer> nums){
for(Integer num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
printList((new Solution()).topKFrequent(nums, k));
}
}
再化簡一點,使用拉姆達表達式替代匿名類
import java.util.*;
public class Solution5 {
public List<Integer> topKFrequent(int[] nums, int k) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int num: nums){
if(map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}
PriorityQueue<Integer> pq = new PriorityQueue<>(
(a, b) -> map.get(a) - map.get(b)
);
for(int key: map.keySet()){
if(pq.size() < k)
pq.add(key);
else if(map.get(key) > map.get(pq.peek())){
pq.remove();
pq.add(key);
}
}
LinkedList<Integer> res = new LinkedList<>();
while(!pq.isEmpty())
res.add(pq.remove());
return res;
}
private static void printList(List<Integer> nums){
for(Integer num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
printList((new Solution()).topKFrequent(nums, k));
}
}
8-9 和堆相關的更多話題和廣義隊列
- d叉堆
- 索引堆
- 二項堆,斐波那契堆
- 廣義隊列
普通隊列,優先隊列
棧,也可以理解成一個隊列。