spring-cloud-kubernetes開發環境搭建
阿新 • • 發佈:2020-11-13
技術標籤:資料結構與演算法分析佇列單調佇列演算法
佇列(Queue)是另一種操作受限的線性表,只允許元素從佇列的一端進,另一端出,因為具有先進先出(FIFO)的特性。
單調佇列(Monotonic Queue)是一種特殊的佇列,它首先是一個佇列,其次佇列內部的元素單調遞增(遞增佇列)或者單調遞減(遞減佇列)。
注意:單調佇列是基於雙端佇列(Deque)實現的。
單調佇列在演算法中的應用在於可以求區間內的最大或者最小值。
// 遞增佇列
for(int i=0; i<nums.length; i++) {
while(!deque.isEmpty() && deque. peekLast() <= nums[i]) {
deque.pollLast();
}
deque.offer(i);
}
// 遞減佇列
for(int i=0; i<nums.length; i++) {
while(!deque.isEmpty() && deque.peekLast() >= nums[i]) {
deque.pollLast();
}
deque.offer(i);
}
在上面的單調佇列中,訪問到任一元素,隊頭peekFirst()
儲存的都是當前的最大值或者最小值。
下面以實際的演算法題說明遞增佇列的作用,這是一道位元組演算法面試題。
LeetCode 239. Sliding Window Maximum(hard)
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1: Example 2:
Input: nums = [1], k = 1 Output: [1]
Example 3:
Input: nums = [1,-1], k = 1 Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2 Output: [11]
Example 5:
Input: nums = [4,-2], k = 2 Output: [4]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> deque = new LinkedList();
int[] res = new int[nums.length-k+1];
for(int i=0; i<nums.length; i++) {
while(!deque.isEmpty() && deque.peekFirst() <= (i-k)) { // maintain the window size
deque.pollFirst();
}
while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
deque.pollLast();
}
deque.offer(i);
if(i+1 >= k) {
res[i+1-k] = nums[deque.peekFirst()];
}
}
return res;
}
}