- 先入先出(FIFO)
- 插入的位置是length+1,删除的位置的是1,一般读取第1个数据元素
循环队列(Circular Queue)
顺序队列的假溢出问题
队列上溢出
- 真上溢:队列真正满时再入队。
- 假上溢:rear已指向队尾,但队列前端仍有空位置。
- 解决假上溢的方法
方法一:每次删除队头一个元素后,把整个队列往前移一个位置(造成时间浪费)。
方法二:使用循环队列方法二:使用循环队列
循环队列-基本思想
循环队列-满与空的判定
循环队列空和满,队头和队尾相连,如何区分?
解决方法
- 另外设置一个标志,以区别队空、队满;
- 少用一个元素空间
队空:front = = rear
队满:(rear+1)%M = = front
优先队列(Priority Queue)
优先队列是正常入,按照优先级出的队列。
实现机制
- Heap(Binary,Binomial,Fibonacci)
- Binary Search Tree
小顶堆(Mini Heap)
大顶堆(Max Heap)
各种堆实现的时间复杂度对比图
java.util.PriorityQueue
java.util.PriorityQueue通过二叉小顶堆实现,可以用一棵完全二叉树表示。
参考:https://www.cnblogs.com/CarpenterLee/p/5488070.html
LeetCode[703]Kth largest Element in a Stream
description
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note
You may assume that nums’ length ≥ k-1 and k ≥ 1.
code
class KthLargest {
final PriorityQueue<Integer> q;
final int k;
public KthLargest(int k, int[] a) {
this.k = k;
q = new PriorityQueue<>(k);
for (int n : a)
add(n);
}
public int add(int n) {
if (q.size() < k)
q.offer(n);
else if (q.peek() < n) {
q.poll();
q.offer(n);
}
return q.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
运行结果:
阻塞队列(Blocking queue)