參考文章:
https://mp.weixin.qq.com/s/80xSoCfeoK_4uIugAU-8nw java實現二叉堆(微信文章 強推看這一篇 )
https://github.com/liuyubobobo/Play-with-Algorithms
https://www.cnblogs.com/g177w/p/8469399.html Java中PriorityQueue詳解(輔助來看)
http://www.importnew.com/25306.html 優先隊列實現原理分析(輔助來看,有時間研究就看)
“ 優先隊列 PriorityQueue ”,跟 “ 堆 Heap ” 的關係, PriorityQuueue 是用 堆 來實現的,插入和刪除元素時不同於普通的隊列。
-----------------------------------ღ( ´・ᴗ・` )比心----------------------------------
推薦一首歌曲,學不進去了,進聽一聽 《醉仙美》 傳送門:https://music.163.com/#/song?id=1351926849
-----------------------------------ღ( ´・ᴗ・` )比心-----------------------------------
溫馨提示:
上面幾篇文章,已經將基本的概念講解的七七八八了,剩下的基本概念不懂就去找視頻,看博客,網上查資料,下面我主要介紹代碼部分。另外,如果代碼看不懂,就拿出紙和筆,好好的畫個圖,將程序多走幾遍就OK了。(如果實在不懂,就問,就百度,就google,反正要搞懂!!!)
堆 Heap 的主體部分:
其中用到的 數組 Array 參考 《一、自己動手實現一個------------“動態數組”》
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 MaxHeap(E[] arr){
data = new Array<>(arr);
for(int i = parent(arr.length - 1) ; i >= 0 ; i --)
siftDown(i);
}
// 返回堆中的元素個數
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 have parent.");
return (index - 1) / 2;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的左孩子節點的索引
private int leftChild(int index){
return index * 2 + 1;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的右孩子節點的索引
private int rightChild(int index){
return index * 2 + 2;
}
// 向堆中添加元素
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);
}
}
// 看堆中的最大元素
public E findMax(){
if(data.getSize() == 0)
throw new IllegalArgumentException("Can not findMax when heap is empty.");
return data.get(0);
}
// 取出堆中最大元素
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;
}
}
// 取出堆中的最大元素,並且替換成元素e
public E replace(E e){
E ret = findMax();
data.set(0, e);
siftDown(0);
return ret;
}
}
優先隊列 PriorityQueue 的代碼實現主體部分:
隊列的接口定義:
public interface Queue<E> {
int getSize();
boolean isEmpty();
void enqueue(E e);
E dequeue();
E getFront();
}
優先隊列 Priority 是利用 二叉堆(最大/小堆Heap)來實現的,
堆的實現參考上面的內容,以下是優先隊列的主體實現部分:
可以看到優先隊列與普通隊列,差別主要是在 插入 和 取出 的時候。
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 maxHeap.extractMax();
}
}
LeetCode 中 利用 優先隊列解決問題的例子:
題目:(就是找出給定非空的整數數組,返回k個出現最頻繁的元素。)
解題思路:利用最小堆,最小堆裏面存儲 K 個 頻繁出現的元素
解題代碼:
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
class Solution {
public class Array<E> {
private E[] data;
private int size;
// 構造函數,傳入數組的容量capacity構造Array
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
// 無參數的構造函數,默認數組的容量capacity=10
public Array(){
this(10);
}
public Array(E[] arr){
data = (E[])new Object[arr.length];
for(int i = 0 ; i < arr.length ; i ++)
data[i] = arr[i];
size = arr.length;
}
// 獲取數組的容量
public int getCapacity(){
return data.length;
}
// 獲取數組中的元素個數
public int getSize(){
return size;
}
// 返回數組是否爲空
public boolean isEmpty(){
return size == 0;
}
// 在index索引的位置插入一個新元素e
public void add(int index, E e){
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");
if(size == data.length)
resize(2 * data.length);
for(int i = size - 1; i >= index ; i --)
data[i + 1] = data[i];
data[index] = e;
size ++;
}
// 向所有元素後添加一個新元素
public void addLast(E e){
add(size, e);
}
// 在所有元素前添加一個新元素
public void addFirst(E e){
add(0, e);
}
// 獲取index索引位置的元素
public E get(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Get failed. Index is illegal.");
return data[index];
}
// 修改index索引位置的元素爲e
public void set(int index, E e){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Set failed. Index is illegal.");
data[index] = e;
}
// 查找數組中是否有元素e
public boolean contains(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return true;
}
return false;
}
// 查找數組中元素e所在的索引,如果不存在元素e,則返回-1
public int find(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return i;
}
return -1;
}
// 從數組中刪除index位置的元素, 返回刪除的元素
public E remove(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed. Index is illegal.");
E ret = data[index];
for(int i = index + 1 ; i < size ; i ++)
data[i - 1] = data[i];
size --;
data[size] = null; // loitering objects != memory leak
if(size == data.length / 4 && data.length / 2 != 0)
resize(data.length / 2);
return ret;
}
// 從數組中刪除第一個元素, 返回刪除的元素
public E removeFirst(){
return remove(0);
}
// 從數組中刪除最後一個元素, 返回刪除的元素
public E removeLast(){
return remove(size - 1);
}
// 從數組中刪除元素e
public void removeElement(E e){
int index = find(e);
if(index != -1)
remove(index);
}
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;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
res.append('[');
for(int i = 0 ; i < size ; i ++){
res.append(data[i]);
if(i != size - 1)
res.append(", ");
}
res.append(']');
return res.toString();
}
// 將數組空間的容量變成newCapacity大小
private void resize(int newCapacity){
E[] newData = (E[])new Object[newCapacity];
for(int i = 0 ; i < size ; i ++)
newData[i] = data[i];
data = newData;
}
}
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 MaxHeap(E[] arr){
data = new Array<>(arr);
for(int i = parent(arr.length - 1) ; i >= 0 ; i --)
siftDown(i);
}
// 返回堆中的元素個數
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 have parent.");
return (index - 1) / 2;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的左孩子節點的索引
private int leftChild(int index){
return index * 2 + 1;
}
// 返回完全二叉樹的數組表示中,一個索引所表示的元素的右孩子節點的索引
private int rightChild(int index){
return index * 2 + 2;
}
// 向堆中添加元素
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);
}
}
// 看堆中的最大元素
public E findMax(){
if(data.getSize() == 0)
throw new IllegalArgumentException("Can not findMax when heap is empty.");
return data.get(0);
}
// 取出堆中最大元素
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;
}
}
// 取出堆中的最大元素,並且替換成元素e
public E replace(E e){
E ret = findMax();
data.set(0, e);
siftDown(0);
return ret;
}
}
public interface Queue<E> {
int getSize();
boolean isEmpty();
void enqueue(E e);
E dequeue();
E getFront();
}
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 maxHeap.extractMax();
}
}
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);
}
PriorityQueue<Freq> pq = new PriorityQueue<>();
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.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));
}
}