队列总结(二)PriorityQueue

PriorityQueue优先级队列的使用和Top-k问题 阅读详情

队列的实现

首先尝试动手写一个类实现Queue接口,发现要实现的方法太多了,麻烦。所幸,JDK为我们提供了一个骨架实现类AbstractQueue,最大限度地减少了实现Queue接口所需的工作。

AbstractQueue

/**
 * 该骨架对于允许null元素的实现来讲是不合适的,其方法add 、 remove和element分别基于offer 、 poll和peek来实现。
 *  所以继承该类的队列实现必须提供一个不允许插入null元素的offer方法
 */
public abstract class AbstractQueue<E>
    extends AbstractCollection<E>
    implements Queue<E> {

    protected AbstractQueue() {
    }
    
    public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

    public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    public E element() {
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    public void clear() {
        while (poll() != null)
            ;
    }

    public boolean addAll(Collection<? extends E> c) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

再找一个基于AbstractQueue的实现PriorityQueue来学习一波。

PriorityQueue

二叉堆实现,理解了二叉堆,这个就实在没什么好讲的了,本质是个最小堆,参考文章https://www.jianshu.com/p/6d3a12fe2d04

但是有几点需要拎出来单独分析一下

	/**
	 * 从队列中移除第 i 个元素。 与常规数组的移除不同,堆的移除操作,首先将最后一个元素e替换到位置i上,同时还要进行下沉或上浮操作以维持堆结构。
	 * 如果在执行上浮或下沉时,元素e恰好都未移位,即最后一个元素替换到i位置上,刚好完美契合堆结构,即此队列的前i-1(包括 i-1)位的元素皆不受影响。在这些情况下,它返回 null。 
	 * 假如在上浮或下沉过程中,元素e与早于 i 的元素(前i-1位)发生了交换。即元素e不在预料的i位置上,而是前i-1的某个位置上。在这些情况下,它返回元素e。 
	 *  这个事实被 iterator.remove 使用,以避免丢失遍历元素。(介绍迭代时会解释)
	 */
    private E removeAt(int i) {
        // assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element
            queue[i] = null;
        else {
            E moved = (E) queue[s];
            queue[s] = null;
            siftDown(i, moved);
            // 说明并未下沉移位
            if (queue[i] == moved) {
                siftUp(i, moved);
                  // 说明发生了上浮移位
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }

我这里提供一个简单例子体会一下:
一个最大堆[8,4,6,2,3,5,1]移除下标1的元素4,这里会发生下沉
一个最大堆[8,4,6,2,5,1,5]移除下标4的元素3,这里会发生上浮
(注意PriorityQueue是个最小堆,如果要测试,注意提供额外的比较器)

package test;

import org.junit.Test;

import java.util.Iterator;
import java.util.PriorityQueue;

public class Client {

    @Test
    public void testUp() {
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> -a.compareTo(b));

        queue.add(8);
        queue.add(4);
        queue.add(6);
        queue.add(2);
        queue.add(3);
        queue.add(5);
        queue.add(1);

        queue.remove(4);
        StringBuilder sb = new StringBuilder();
        for (int i : queue) {
            sb.append(i).append(",");
        }
        System.out.println(sb);
    }

    @Test
    public void testDown() {
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> -a.compareTo(b));

        queue.add(8);
        queue.add(4);
        queue.add(6);
        queue.add(2);
        queue.add(3);
        queue.add(1);
        queue.add(5);

        queue.remove(3);
        StringBuilder sb = new StringBuilder();
        for (int i : queue) {
            sb.append(i).append(",");
        }
        System.out.println(sb);
    }

    @Test
    public void testItr() {
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> -a.compareTo(b));

        queue.add(8);
        queue.add(4);
        queue.add(6);
        queue.add(2);
        queue.add(3);
        queue.add(1);
        queue.add(5);

        StringBuilder sb = new StringBuilder();
        Iterator<Integer> iterator = queue.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next == 3) {
                iterator.remove();
            }
            sb.append(next).append(",");
        }
        System.out.println(sb);
    }

}

迭代器的实现(偷个懒,懒得写分析了)

    private final class Itr implements Iterator<E> {
        /**
         * Index (into queue array) of element to be returned by
         * subsequent call to next.
         */
        private int cursor = 0;

        /**
         * Index of element returned by most recent call to next,
         * unless that element came from the forgetMeNot list.
         * Set to -1 if element is deleted by a call to remove.
         */
        private int lastRet = -1;

        /**
         * A queue of elements that were moved from the unvisited portion of
         * the heap into the visited portion as a result of "unlucky" element
         * removals during the iteration.  (Unlucky element removals are those
         * that require a siftup instead of a siftdown.)  We must visit all of
         * the elements in this list to complete the iteration.  We do this
         * after we've completed the "normal" iteration.
         *
         * We expect that most iterations, even those involving removals,
         * will not need to store elements in this field.
         */
        private ArrayDeque<E> forgetMeNot = null;

        /**
         * Element returned by the most recent call to next iff that
         * element was drawn from the forgetMeNot list.
         */
        private E lastRetElt = null;

        /**
         * The modCount value that the iterator believes that the backing
         * Queue should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        private int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor < size ||
                (forgetMeNot != null && !forgetMeNot.isEmpty());
        }

        @SuppressWarnings("unchecked")
        public E next() {
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
            if (cursor < size)
                return (E) queue[lastRet = cursor++];
            if (forgetMeNot != null) {
                lastRet = -1;
                lastRetElt = forgetMeNot.poll();
                if (lastRetElt != null)
                    return lastRetElt;
            }
            throw new NoSuchElementException();
        }

        public void remove() {
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
            if (lastRet != -1) {
                E moved = PriorityQueue.this.removeAt(lastRet);
                lastRet = -1;
                if (moved == null)
                    cursor--;
                else {
                    if (forgetMeNot == null)
                        forgetMeNot = new ArrayDeque<>();
                    forgetMeNot.add(moved);
                }
            } else if (lastRetElt != null) {
                PriorityQueue.this.removeEq(lastRetElt);
                lastRetElt = null;
            } else {
                throw new IllegalStateException();
            }
            expectedModCount = modCount;
        }
    }

java优先队列 PriorityQueue详解(附图) 文章目录前言一、概念及应用场景二、原理及源码分析1. 了解继承图2. 优先队列的插入总结 前言 最近接触到优先队列的题目,正好趁这个机会复习一下优先队列,并深入了解一下源码。 一、概念及应用场景 PriorityQueue翻译过来是优先队列,是队列中的一种特殊队列。PriorityQueue里的元素是有序的,默认情况下是单调增,可以通过传入Comparator根据自己的需求来更改。 在概念上,它是一个有序的二叉树,这种顺序的规则是(默认情况下),每个节点的值都比它的孩子节点的值小。一个最小堆如下图所示. 阅读详情

相关推荐

Anaconda+Pycharm安装

我提前创建好一个自己项目所需的虚拟环境。步骤是:打开终端(cmd)或者 搜索 ”Anaconda Prompt“ 并打开,输入 conda create -n pytorch python=3.9 -c。

Wang_sweet的博客 3233

PriorityQueue源码分析

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录前言一、offer(E e)二、poll()1.引入库总结 前言 主要分析offer(E e) 和 poll() 两个防范 一、offer(E e) offer(E e)源码如下 public boolean offer(E e) { if (e == null) throw new NullPointerException(); modCount++;

huyang0101的博客 329

手把手教你用差分放大电路搭建LC振荡器(实测频率误差分析)

本文通过一个差分放大电路搭建LC振荡器的实践案例,深入分析了实测频率与理论值产生显著误差的原因。核心在于共模电感的互感效应改变了谐振回路的等效电感,导致频率偏差。文章提供了从电路搭建、误差根源剖析到波形优化与稳定性提升的完整解决方案,帮助电子爱好者深入理解模拟电路的实际行为。

svm4gardener的博客 542

【Java 集合 & 数据结构】优先队列 PriorityQueue

优先队列 PriorityQueue 是 接口 Queue的实现,可以对其中元素进行排序,可以放基本的包装类型或自定义类型,对于包装类型默认为升序,对于自定义类型需手动实现 Comparator 接口。

茶色喵的博客 1953

OpenManus本地部署实战:从源码编译到浏览器路径优化全解析

本文详细解析了OpenManus本地部署的全过程,从源码编译到浏览器路径优化。涵盖环境准备、源码获取、模型配置、依赖安装等关键步骤,特别针对Windows系统下的chrome.exe路径修改提供了实用解决方案,帮助开发者高效完成部署并优化性能。

weixin_28826545的博客 381

Nvidia Jetson CH340 驱动安装

最近调一个USB设备,Windows系统上是可以安装CH340 驱动使用的,移到Jetson AGX Orin 上发现没有 /dev/ttyUSB* 设备显示。是一个为盲人和视力障碍者提供的终端设备驱动程序,它会在系统启动时自动加载并占用串口设备,导致我们无法正常使用部分串口设备。安装完后,内核中已经有。

Vulcan_S的博客 1639

Java - 重要集合:PriorityQueue

Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的通过观察源码:使用必须导包!堆有很多方法的,接下来我们将学习堆!PriorityQueue中放置的元素必须要能够比较大小,,否则会抛出ClassCastException异常,否则会抛出NullPointerException没有容量限制,可以插入任意多个元素,其内部可以自动扩容。

kaiwawah的博客 561

【unity实战】完美的2D横版平台跳跃玩家控制器,使用InputSystem+有限状态机实现人物加速减速 多段跳 长短跳 多段攻击 冲锋 冲锋残影 滑墙 蹬墙跳 滑墙 土狼时间 预输入 攀爬 爬楼梯

【unity实战】使用unity的新输入系统InputSystem+有限状态机设计一个玩家状态机控制——实现玩家的待机 移动 闪避 连击 受击 死亡状态切换这次来实现一个2d平台平台跳跃玩家控制器,平台人物控制要做的好,要考虑的问题会有很多,比如移动加速减速 多段跳 冲锋 冲锋残影 滑墙 蹬墙跳 土狼时间 预输入 攀爬 爬楼梯//减速至于为什么叫这个名字(土狼时间)呢?其实这个名词来自于华纳兄弟动画公司,一部古老的动画系列影片《Looney Tunes》

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 6044

PriorityQueue详解

PriorityQueue是优先队列,作用是保证每次取出的元素都是队列中权值最小的,这里涉及到了大小关系,元素大小的评判可以通过元素自身的自然顺序(使用默认的比较器),也可以通过构造时传入的比较器。Java中PriorityQueue实现了Queue接口,不允许放入null元素;其通过堆实现,具体说是通过完全二叉树(complete binary tree)实现的小顶堆(任意一个非叶子节点的权值,都不大于其左右子节点的权值),也就意味着可以通过数组来作为PriorityQueue的底层实现。

yzx3105的博客 902

一次搞定 SAP IDoc 失败重处理与安全清理:BD87 实战指南

本文介绍了SAP IDoc错误处理的BD87实战指南。主要内容包括: BD87的核心功能:监控IDoc处理状态并支持人工重处理或标记删除,适用于入站/出站IDoc故障处理。 重处理前的关键步骤: 区分技术错误与业务错误 检查是否允许重复处理 确认日期范围设置正确 标准操作流程:通过BD87选择错误IDoc节点执行重处理,特别适用于状态51的应用错误。 标记删除操作:将无用IDoc标记为可清理状态,后续可通过WE11物理删除或归档处理。 常见问题解决方案:包括权限控制、批量处理优化建议以及自动化定位工具的开发

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 456

FPGA实现串口升级及MultiBoot(十)串口升级SPI FLASH实现

采用软核进行串口升级的原因主要有以下几点:1、官方推荐:官方以前也推出了针对逻辑进行升级的程序《XAPP1081_QuickBoot》,但是从今年起(2024年)官方就停止更新相关例程了(详见下面截图),所以采用官方推荐的软核更新;2、简单并具有通用性:针对SPI或者BPI官方都有相关的IP,可应对市场上80%以上的FLASH,并且官方IP通用性极强,只需要修改几个参数就可以对不同厂家的芯片进行升级操作;

OpenFPGA的博客 2000

数据结构——优先队列PriorityQueue

PriorityQueue 底层原理是二叉堆 继承AbstractQueue抽象类,实现Serializable接口 AbstractQueue继承AbstractCollection抽象类,实现Queue接口 AbstractCollection实现Collection接口 主要方法为offer(E e),peek(),poll() 源码分析offer(E e)——插入元素 public b

seaking_fade的博客 347

最适合入门的100个深度学习项目

本专栏整理了《PyTorch深度学习项目实战100例》,内包含了各种不同的深度学习项目,包含项目原理以及源码,每一个项目实例都附带有完整的代码+数据集。

优快云 精品推荐 12万+

优先级队列PriorityQueue(堆)(二)

PriorityQueue的特性,PriorityQueue常用接口介绍,优先级队列的构造,插入/删除/获取优先级最高的元素,PriorityQueue扩容方式,oj练习,堆的应用,PriorityQueue的实现,堆排序,Top-k问题

Romised的博客 778

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

[Queue] 1.优先队列PriorityQueue(非先进先出) 2.普通队列LinkedList的添加 遍历 删除 查看(先进先出)

package org.example.testPriorityQueue; import java.util.PriorityQueue; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<Integer> queue = new PriorityQueue<>((v1, v2) -> v2 - v1); .

focus-unchanged-thing 309

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

延时队列的实现

当接收到消息之后,我需要隔一段时间进行处理(相对于立马处理,它隔了一段时间,所以他叫延迟消息)。

yzx3105的博客 341

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Java 优先队列(PriorityQueue)总结

PriorityQueue 实现的是 Queue 接口 ,可以使用 Queue 提供的方法,以及自带的方法。 1、PriorityQueue概述 Java PriorityQueue 实现了 Queue 接口,不允许放入 null 元素;其通过堆实现,具体说是 通过完全二叉树(complete binary tree)实现的小顶堆(任意一个非叶子节点的权值,都不 大于其左右子节点的权值),也就意味着可以通过数组来作为PriorityQueue 的底层实现, 数组初始大小为11;也可以用一棵完全二叉树表示。

qq_36511997的博客 2万+

Java优先队列(PriorityQueue)

参考 http://www.importnew.com/6932.html https://www.cnblogs.com/gnivor/p/4841191.html 我们知道队列是遵循先进先出(First-In-First-Out)模式的,但有些时候需要在队列中基于优先级处理对象。举个例子,比方说我们有一个每日交易时段生成股票报告的应用程序,需要处理大量数据并且花费很多处理时间。客户向这个应用程......

try to do 3万+

数据结构优先级队列PriorityQueue

我们使用大根堆来进行排序,将0下标值与最后下标值进行交换,end为最后下标值,然后向下筛选重新获取最大的节点值,每次的有效元素数量-1(由最后一个下标开始–直到为0,获取由小到大的元素)。而优先级队列(PriorityQueue)指的是具有优先级别的队列(特殊队列),根据指定类型的大小,每次出队的元素都是该类型中最大或者是最小的值,具有优先级。删除元素我们可以将对首的元素将队尾的元素进行互换,并将队尾元素的下标值删除,后续进行覆盖,然后通过向下筛选,设定根节点为0下标互换的位置,进行向下筛选。

Freedom的博客 3201

Java PriorityQueue(优先队列)

Java PriorityQueue类是一种队列数据结构实现,其中根据优先级处理对象。它与遵循FIFO(先进先出)算法的标准队列不同。 在优先级队列中,添加的对象根据其优先级。默认情况下,优先级由对象的自然顺序决定。队列构建时提供的比较器可以覆盖默认优先级。 优先级队列 1. PriorityQueue功能 让我们记下PriorityQueue上的几个要点。 PriorityQueu...

javaZhong的博客 6万+

PriorityQueue(优先队列)

我们都知道队列是一种先进先出的数据结构,没有优先级,众数据平等. 但是在某些情况下,我们操作的数据可能带有优先级,出队列时要优先级高的先出,低的后出. 在这种情况下,我们的数据结构应该提供两个最基本的操作,一个是返回最高优先级对象,一个是添加新的对象.这种数据结构就是我们今天要介绍的优先级队列.在Java的集成框架中主要有两种类型的优先级队列,分别为:PriorityQueue和PriorityBlockingQueue PriorityQueue是线程不安全的,PriorityBlockingQueue是

Hello World! 8339

优先级队列(PriorityQueue)和堆

前面介绍过队列,是一种先进先出(FIFO)的数据结构,但有些情况下,操作的数据可能带有,一般出队列时,可能需要优先级高的元素先出队列,该中场景下,使用队列显然不合适,比如:在手机上玩游戏的时候,如果有来电,那么系统应该优先处理打进来的电话;初中那会班主任排座位时可能会让成绩好的同学先挑座位。在这种情况下,数据结构应该提供两个最基本的操作,一个是返回最高优先级对象,一个是添加新的对象。这种数据结构就是。

weixin_63189874的博客 3310

Java优先队列PriorityQueue使用详解

目录 一、优先队列概述   简介: API描述: 二、常用方法 构造方法: 方法摘要: 三、优先队列的使用 1.队列保存的是基本数据类型的包装类 2.队列保存的是自定义类 3.优先队列遍历 4.比较器生降序说明 一、优先队列概述   简介: 优先队列PriorityQueue是Queue接口的实现,可以对其中元素进行排序,可以放基本数据类型的包装类(如:Integer,Long等)或自定义的类。对于基本数据类型的...

qq_22596931的博客 1万+

PriorityQueue优先队列详解

是一个基于优先级堆(通常是最小堆)的无界队列。它不允许null元素,并且要求所有放入的元素要么实现Comparable接口,要么在构造时提供一个Comparator。是Java集合框架中非常实用的一个数据结构,它基于优先级对元素进行排序,在许多应用场景中都有着广泛的应用。通过掌握的使用和原理,我们可以更加灵活地处理任务调度、路径搜索等问题。如果你有任何问题或建议,欢迎在评论区留言讨论。

微赚淘客开发者博客 1653

java优先队列PriorityQueue中Comparator的用法

在使用java的优先队列PriorityQueue的时候,会看到这样的用法。 PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2){ ...

衣衫破旧 歌声温柔 8833

[java队列]——PriorityQueue

[java队列]——PriorityQueuePriorityQueue介绍PriorityQueue内部实现基本属性构造方法入队扩容出队取队头元素,并不出队PriorityQueue总结Queue接口 PriorityQueue介绍 上一篇[java队列]——ArrayBlockingQueue介绍了数组方式实现的阻塞队列。这篇将介绍PriorityQueue优先级队列。其简介如下: 优先级队...

way2016的博客 491
上一篇: 序列化writeObject与readObject
下一篇: 队列总结(三)ArrayDeque
MrMoving
博客等级 码龄10年 54粉丝 145原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值