PriorityQueue

简要介绍

Java中PriorityQueue通过二叉小顶堆实现,可以用一棵完全二叉树表示。

优先队列的作用是能保证每次取出的元素都是队列中权值最小的。牵涉到的大小关系,元素大小的评判可以通过元素本身的自然顺序,也可以通过构造时传入的比较器(Comparator,实现的比较接口)。

Java中PriorityQueue实现了Queue接口,不允许放入null元素。

PriorityQueue的peek()和element()操作是常数时间,add(), offer(), 无参数的remove()以及poll()方法的时间复杂度都是log(N)。

具体接口

1.创建对象

PriorityQueue<Integer> queue1=new PriorityQueue<>((a, b) -> (b-a));//大根堆
PriorityQueue<Integer> queue2=new PriorityQueue<>((a, b) -> (a-b));//小根堆

代码中的lambda表达式也可以通过写好的Comparator接口来代替。

2.插入元素

add(E e)和offer(E e)的功能相同,前者在插入失败时抛出异常,后则则会返回false。对于PriorityQueue没有区别。

public boolean offer(E e) {
    if (e==null)
        throw new NullPointerException();
    modCount++;
    int i = size;
    if (i >= queue.length)
        grow(i + 1);
    size = i + 1;
    if (i == 0)
        queue[0] = e;
    else
        siftUp(i, e);
    return true;
}

其中,grow()是一个扩容函数,其内容是申请一个更大的数组,将原数组赋值过去。而siftUp()代码如下,作用是调整,通过代码可以发现就是熟悉的一个堆的操作了。

private void siftUp(int k, E x) {
    while (k > 0) {
        int parent = (k - 1) >>> 1;
        Object e = queue[parent];
        if (comparator.compare(x, (E) e) >= 0)
            break;
        queue[k] = e;
        k = parent;
    }
    queue[k] = x;
}

3.获取堆顶元素

element()和peek()的功能相同,都是获取但不删除队首元素,也就是队列中权值最小的那个元素,二者唯一的区别是当方法失败时前者抛出异常,后者返回null。

public E peek() {
    if (size == 0)
        return null;
    return (E) queue[0];
}

4.获取并删除堆顶元素

remove()和poll()方法的功能相同,都是获取并删除队首元素,区别是当方法失败时前者抛出异常,后者返回null。

public E poll() {
    if (size == 0)
        return null;
    int s = --size;
    modCount++;
    E result = (E) queue[0];
    E x = (E) queue[s];
    queue[s] = null;
    if (s != 0)
        siftDown(0, x);
    return result;
}

其中siftdown()也是一个调整的函数。

private void siftDown(int k, E x) {
    int half = size >>> 1;
    while (k < half) {
        int child = (k << 1) + 1;//leftNo = parentNo*2+1
        Object c = queue[child];
        int right = child + 1;
        if (right < size &&
            comparator.compare((E) c, (E) queue[right]) > 0)
            c = queue[child = right];
        if (comparator.compare(x, (E) c) <= 0)
            break;
        queue[k] = c;
        k = child;
    }
    queue[k] = x;
}

5.删除某一个指定的元素

remove(Object o)方法用于删除队列中跟o相等的某一个元素(如果有多个相等,只删除一个),该方法不是Queue接口内的方法,而是Collection接口的方法。

public boolean remove(Object o) {
    int i = indexOf(o);
    if (i == -1)
        return false;
    int s = --size;
    if (s == i)
        queue[i] = null;
    else {
        E moved = (E) queue[s];
        queue[s] = null;
        siftDown(i, moved);
        ......
    }
    return true;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值