單調棧模板
Stack<Interger> stack=new stack<>();
for(int i=0;i<nums.length;i++){
while(!stack.empty()&&nums[i]>stack.peek()){
//記錄結果
}
stack.push(nums[i]);
}
while(!stack.empty()){
//處理剩餘元素
}
相關題型
下一個更大的元素
題目描述:496. 下一個更大元素 I
給定兩個 沒有重複元素 的數組 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每個元素在 nums2 中的下一個比其大的值。
nums1 中數字 x 的下一個更大元素是指 x 在 nums2 中對應位置的右邊的第一個比 x 大的元素。如果不存在,對應位置輸出 -1 。
輸入: nums1 = [4,1,2], nums2 = [1,3,4,2].
輸出: [-1,3,-1]
解釋:
對於num1中的數字4,你無法在第二個數組中找到下一個更大的數字,因此輸出 -1。
對於num1中的數字1,第二個數組中數字1右邊的下一個較大數字是 3。
對於num1中的數字2,第二個數組中沒有下一個更大的數字,因此輸出 -1。
public class Solution{
public int[] nextGreaterElement(int[] findNums,int [] nums){
Stack<Interger> stack=new stack<>();
HashMap<Integer,Integer> map=new HashMap<>();
int[] res=new int[findNums.length];
for(int i=0;i<nums.length;i++){
while(!stack.empty()&&nums[i]>stack.peek()){
map.put(stack.pop(),nums);
}
stack.push(nums[i]);
}
while(!stack.empty()){
map.put(stack.pop(),-1);
}
for(int i=0;i<findNums.length;i++){
res[i]=map.get(findNums);
}
return res;
}
}
每日溫度
題目描述:739. 每日溫度
請根據每日 氣溫 列表,重新生成一個列表。對應位置的輸出爲:要想觀測到更高的氣溫,至少需要等待的天數。如果氣溫在這之後都不會升高,請在該位置用 0 來代替。
例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的均爲華氏度,都是在 [30, 100] 範圍內的整數。
class Solution {
public int[] dailyTemperatures(int[] T) {
if(T==null||T.length<=0){
return new int[0];
}
int len=T.length;
int[] res=new int[len];
Stack<Integer> stack=new Stack<>();
int index=0;
for(int i=0;i<len;i++){
while(!stack.isEmpty()&&T[i]>T[stack.peek()]){
res[stack.peek()]=i-stack.pop();
}
stack.push(i);
}
while(!stack.isEmpty()){
res[stack.pop()]=0;
}
return res;
}
}
股票價格跨度
題目鏈接:901. 股票價格跨度
編寫一個 StockSpanner 類,它收集某些股票的每日報價,並返回該股票當日價格的跨度。
今天股票價格的跨度被定義爲股票價格小於或等於今天價格的最大連續日數(從今天開始往回數,包括今天)。
例如,如果未來7天股票的價格是 [100, 80, 60, 70, 60, 75, 85],那麼股票跨度將是 [1, 1, 1, 2, 1, 4, 6]。
注意這道題目是包括今天,往前看,因此今天的加工應該大於之前的價格。包括今天的話,跨度的初始值應爲1
class StockSpanner {
private Stack<Integer> prices;
private Stack<Integer> weights;
public StockSpanner() {
prices=new Stack<Integer>();
weights=new Stack<Integer>();
}
public int next(int price) {
int w=1;
while(!prices.isEmpty()&&price>prices.peek()){
prices.pop();
w+=weights.pop();
}
prices.push(price);
weights.push(w);
return w;
}
}