Java實現小根堆和大根堆(PriorityQueue)

Java裏面的PriorityQueue底層默認使用的堆,所以我們使用PriorityQueue就能實現堆的功能。

1、小根堆實現

package test;

import java.util.Comparator;
import java.util.PriorityQueue;

/*
    add 增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
    remove 移除並返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常
    element 返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常
    offer 添加一個元素並返回true 如果隊列已滿,則返回false
    poll 移除並返問隊列頭部的元素 如果隊列爲空,則返回null
    peek 返回隊列頭部的元素 如果隊列爲空,則返回null
 */
public class Test {

    public static void main(String[] args) {

        PriorityQueue<Integer>priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

        for(int i = 10; i >= 0; i--){
            if(priorityQueue.size() < 5){
                priorityQueue.add(i);
            }else {
                priorityQueue.remove();
                priorityQueue.add(i);
            }
        }

        while (!priorityQueue.isEmpty()) {
            System.out.println(priorityQueue.remove());
        }
    }
}

2、大根堆

package test;

import java.util.Comparator;
import java.util.PriorityQueue;

/*
    add 增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
    remove 移除並返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常
    element 返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常
    offer 添加一個元素並返回true 如果隊列已滿,則返回false
    poll 移除並返問隊列頭部的元素 如果隊列爲空,則返回null
    peek 返回隊列頭部的元素 如果隊列爲空,則返回null
 */
public class Test {

    public static void main(String[] args) {

        PriorityQueue<Integer>priorityQueue = new PriorityQueue<>();

        for(int i = 0; i < 10; i++){
            if(priorityQueue.size() < 5){
                priorityQueue.add(i);
            }else {
                priorityQueue.remove();
                priorityQueue.add(i);
            }
        }

        while (!priorityQueue.isEmpty()) {
            System.out.println(priorityQueue.remove());
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章