文章目錄
- 堆(優先級佇列)
- 1.二叉樹的順序存盤
- 1.1 存盤方式
- 1.2 下標的關系
- 2.堆
- 2.1 概念
- 3.模擬實作PriorityQueue
- ①基本操作
- ②向下調整
- ③建堆
- ④入佇列
- ⑤出佇列
- ⑥堆排序
- 4.堆的應用-優先級佇列
- 4.1 java 中的優先級佇列
- 4.2 java 中堆的使用
- 5. 集合框架中PriorityQueue的比較方式
- 6.堆的其他應用-TopK 問題
- 用堆的思路:
- 畫圖決議:
- 代碼實作:
- 運行結果:
- 7.面試題---查找和最小的K對數字
- 解題思路:
- 代碼實作:
堆(優先級佇列)
1.二叉樹的順序存盤
1.1 存盤方式
使用陣列保存二叉樹結構,方式即將二叉樹用層序遍歷方式放入陣列中,
一般只適合表示完全二叉樹,因為非完全二叉樹會有空間的浪費,
這種方式的主要用法就是堆的表示,

1.2 下標的關系
- 如果 已知雙親下標(parent) ,則:
左孩子的下標(left child) = 2 * parent + 1;
右孩子的下標(right child) = 2 * parent + 2; - 如果 已知任意孩子下標(child),則:
雙親的下標(parent) = ( child - 1 ) / 2;

2.堆
2.1 概念
- 堆邏輯上是一棵完全二叉樹
- 堆物理上是保存在陣列中
- 滿足任意結點的值都大于其子樹中結點的值,叫做大堆,或者大根堆,或者最大堆
- 反之,則是小堆,或者小根堆,或者最小堆
- 堆的基本作用是,快速找集合中的最值

3.模擬實作PriorityQueue
①基本操作
class TestHeap {
public int[] elem;
public int usedSize;
public TestHeap(){
this.elem = new int[10];
}
}
②向下調整
思路:

代碼實作:
//len是有效資料長度
public void adjustDown(int root,int len) {
int parent = root;
int child = 2 * parent + 1;
while(child < len){
//找到左右孩子的最大值
//1. 沒有右孩子,左孩子就是最大.child下標下就是最大
//2. 有右孩子,但是左孩子更大,即左孩子是最大.child下標下就是最大
//3. 有右孩子,但是右孩子更大,即右孩子是最大.child+1 下標下就是最大
if(child+1 < len && this.elem[child] < this.elem[child+1]){
child++;
}
//此時child下標下就是最大值.
if(this.elem[child] > this.elem[parent]){
int tmp = this.elem[child];
this.elem[child] = this.elem[parent];
this.elem[parent] = tmp;
parent = child;
child = 2 * parent + 1;
}else {
break;
}
}
}
③建堆
建大堆 - 思路:
從最后一個資料的 雙親開始 向下調整. 每次調整完 讓parent-- 直到調整到parent = 0;
/**
* 建大堆
* @param array
*/
public void createHeap(int[] array){
//這一步相當于 陣列的拷貝
for (int i = 0; i < array.length; i++) {
this.elem[i] = array[i];
this.usedSize++;
}
//parent 就代表每顆子樹的根節點
for (int parent = (array.length-1-1)/2;parent >= 0; parent--) {
adjustDown(parent,this.usedSize);
}
}
時間復雜度的分析:

④入佇列
思路:從隊尾入,每次入佇列都要進行向上調整
向上調整:
① 如果插入的child比parent大 則需要交換
② 交換后需要讓child = parent; parent = (child - ) / 2;
③ 如果插入的child比parent小 則不需要交換
④回圈①②③操作,直到不需要交換或則 child<0結束回圈.
代碼實作:
public void adjustUp(int child){
//parent等于child的雙親
int parent = (child - 1) / 2;
//child>0進入回圈
while(child > 0) {
if (this.elem[child] > this.elem[parent]){
int tmp = this.elem[parent];
this.elem[parent] = this.elem[child];
this.elem[child] = tmp;
child = parent;
parent = (child - 1) / 2;
}else {
//不需要交換直接跳出回圈
break;
}
}
}
入隊思路:
1.首先判斷是否需要擴容
2.如果需要擴容則要先擴容然后插入,不需要擴容直接插入
3.插入后進行向上調整
代碼實作:
public void push(int val){
if(isFull()){
//擴容
Arrays.copyOf(this.elem,2*this.elem.length);
}
//插入 向上調整
this.elem[this.usedSize++] = val;
adjustUp(usedSize - 1);
}
//判斷是否滿
public boolean isFull(){
return this.usedSize == this.elem.length;
}
⑤出佇列
出佇列思路:
1.首先需要判斷是否為空
2.為空直接回傳
3.不為空,首先交換隊首元素和隊尾元素,然后從0下標開始進行向下調整.
代碼實作:
//判斷是否為空
public boolean isEmpty(){
return this.usedSize == 0;
}
public void pop(){
if(!isEmpty()){
//不為空首先進行交換
int tmp = this.elem[0];
this.elem[0] = this.elem[usedSize - 1];
this.elem[usedSize - 1] = tmp;
this.usedSize--;
//然后進行向下調整
adjustDown(0,this.usedSize);
}
}
⑥堆排序
堆排序思路:
1.讓end指向隊尾元素
2.讓隊首元素和end交換
3.從0下標位置進行向下調整 然后end–;
4.重復以上操作直到end=0;
代碼實作:
/**
* 前提是要先創建大堆
*/
public void heapSort() {
int end = this.usedSize - 1;
while(end > 0) {
int tmp = this.elem[0];
this.elem[0] = this.elem[end];
this.elem[end] = tmp;
adjustDown(0,end--);
}
}
4.堆的應用-優先級佇列
4.1 java 中的優先級佇列
PriorityQueue implements Queue
| 錯誤處理 | 拋出例外 | 回傳特殊值 |
|---|---|---|
| 入佇列 | add(e) | offer(e) |
| 出佇列 | remove() | poll() |
| 隊首元素 | element() | peek() |
4.2 java 中堆的使用
注意:
1. 堆的默認大小是 11 默認為小堆
2. 可以指定堆的大小,可以指定堆為大小堆.
public static void main (String[] args) {
//堆 默認是大小為11
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
//默認是 小堆
priorityQueue.add(1);
priorityQueue.add(2);
priorityQueue.add(3);
System.out.println(priorityQueue);
}
5. 集合框架中PriorityQueue的比較方式
集合框架中的PriorityQueue底層使用堆結構,因此其內部的元素必須要能夠比大小,PriorityQueue采用了:
Comparble和Comparator兩種方式,
- Comparble是默認的內部比較方式,如果用戶插入自定義型別物件時,該類物件必須要實作Comparble接
口,并覆寫compareTo方法 - 用戶也可以選擇使用比較器物件,如果用戶插入自定義型別物件時,必須要提供一個比較器類,讓該類實作
Comparator介面并覆寫compare方法,


6.堆的其他應用-TopK 問題
TopK問題,找前K個最大(最小)的數.
用堆的思路:
- 放入k個元素到堆中
①找前k個最大的數,建小堆.
②找前k個最小的數,建大堆. - 如果找的是前k個最大的數,先建小堆將k個元素放入堆中,然后讓堆頂元素 和 后面的數比較,如果小于后面的數,就和堆頂元素交換,然后變成小堆繼續此操作.
- 反之則是找前k個最小的數.
- 遍歷結束后,堆中的元素就是要找的數
畫圖決議:

代碼實作:
/**
* 找前k個最大的元素
* @param array
* @param k
*/
public static void topk2(int[] array,int k){
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;//大堆
}
});
for (int i = 0; i < array.length; i++) {
if (maxHeap.size() < k) {
maxHeap.offer(array[i]);
} else {
int top = maxHeap.peek();//獲取隊頂元素
if (top < array[i]) {
maxHeap.poll();
maxHeap.offer(array[i]);
}
}
}
System.out.println(maxHeap);
}
/**
* 找前k個最小的元素
* @param array
* @param k
*/
public static void topk1(int[] array,int k){
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;//大堆
}
});
for (int i = 0; i < array.length; i++) {
if (maxHeap.size() < k) {
maxHeap.offer(array[i]);
} else {
int top = maxHeap.peek();//獲取隊頂元素
if (top > array[i]) {
maxHeap.poll();
maxHeap.offer(array[i]);
}
}
}
System.out.println(maxHeap);
}
public static void main(String[] args) {
int[] array = {1,3,2,6,5,78,22,15,28};//找前3個最大的資料.
topk1(array,3);
topk2(array,4);
}
運行結果:

7.面試題—查找和最小的K對數字
LeetCode 373: 查找和最小的K對數字
描述:
給定兩個以升序排列的整數陣列 nums1 和 nums2 , 以及一個整數 k ,
定義一對值 (u,v),其中第一個元素來自 nums1,第二個元素來自 nums2 ,
請找到和最小的 k 個數對 (u1,v1), (u2,v2) … (uk,vk) ,
示例 1:
輸入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
輸出: [1,2],[1,4],[1,6]
解釋: 回傳序列中的前 3 對數:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
解題思路:
- 根據題意找最小的k對數字,建立大小為k的大堆
- 如果堆沒放滿,直接放入堆中.
- 如果堆放滿了,每次需要和堆頂比較,如果小于堆頂,需要交換.
- 遍歷時注意,如果陣列過大,遍歷會超時,所以遍歷次數可以優化為 只最多遍歷到 k,而且要滿足小于陣列長度的要求.(i<k && i<nums.length)
- 在遍歷結束后,將資料插入list中的時候注意.可能堆沒滿.
代碼實作:
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<List<Integer>> MaxHeap = new PriorityQueue<>(k, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return (o2.get(0) + o2.get(1)) - (o1.get(0) + o1.get(1));
}
});
// 只最多遍歷到 k,而且要滿足小于陣列長度的要求
for (int i = 0; i < nums1.length && i < k; i++) {
for (int j = 0; j < nums2.length && j < k; j++) {
// 堆沒滿 首先放入堆中
if (MaxHeap.size() < k){
List<Integer> list1 = new ArrayList<>();
list1.add(nums1[i]);
list1.add(nums2[j]);
MaxHeap.offer(list1);
}else {
List<Integer> top = MaxHeap.peek();
int topValue = top.get(0) + top.get(1);
//堆滿了后要進行比較,大于堆頂的值要出隊然后把大于的資料入隊
if(topValue > nums1[i] + nums2[j]){
MaxHeap.poll();
List<Integer> list1 = new ArrayList<>();
list1.add(nums1[i]);
list1.add(nums2[j]);
MaxHeap.offer(list1);
}
}
}
}
//將資料放入ret中要注意 可能堆沒放滿
List<List<Integer>> ret = new ArrayList<>();
for (int i = 0; i < k && !MaxHeap.isEmpty(); i++) {
ret.add(MaxHeap.poll());
}
return ret;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/397351.html
標籤:其他
上一篇:Log4j 2再現新漏洞;缺乏資助不是開源軟體安全的唯一問題;微軟公布 Entity Framework 7.0 計劃 | 開源日報
