資料結構與演算法-佇列
-
定義
佇列是ListInsert發生表尾、ListDelete發生在表頭的線性表,主要操作:入隊、出隊。 -
術語
表頭-隊頭,表尾-隊尾,插入-入隊,刪除-出隊 -
特點
- 先入先出(FIFO)
- 插入的位置是length+1,刪除的位置的是1,一般讀取第1個數據元素
迴圈佇列(Circular Queue)
順序佇列的假溢位問題
佇列上溢位
- 真上溢:佇列真正滿時再入隊。
- 假上溢:rear已指向隊尾,但佇列前端仍有空位置。
- 解決假上溢的方法
方法一:每次刪除隊頭一個元素後,把整個佇列往前移一個位置(造成時間浪費)。
方法二:使用迴圈佇列方法二:使用迴圈佇列
迴圈佇列-基本思想
- 首位相連:把a[0]和a[5]想象成鄰居
迴圈佇列-滿與空的判定
迴圈佇列空和滿,隊頭和隊尾相連,如何區分?
解決方法
- 另外設定一個標誌,以區別隊空、隊滿;
- 少用一個元素空間
隊空:front = = rear
隊滿:(rear+1)%M = = front
優先佇列(Priority Queue)
優先佇列是正常入,按照優先順序出的佇列。
實現機制
- Heap(Binary,Binomial,Fibonacci)
- Binary Search Tree
小頂堆(Mini Heap)
大頂堆(Max Heap)
各種堆實現的時間複雜度對比圖
java.util.PriorityQueue
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);
*/
執行結果: