class Solution {
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
int[] res = new int[len];
Deque<Integer> stack = new LinkedList<>();
Arrays.fill(res,-1);
for(int i = 0 ;i<len*2; i++){
//循环数用取模的方式
int j = i % len;
while(!stack.isEmpty() && nums[j] > nums[stack.peek()] ){
res[stack.peek()] = nums[j];
stack.pop();
}
stack.push(j);
}
return res;
}
}
class Solution {
public int trap(int[] height) {
int res = 0;
if (height.length <= 2) return res;
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
for(int i = 0 ;i<height.length;i++){
if(stack.isEmpty() || height[i] <= height[stack.peek()]){
//如果栈为空,或当前柱子小于上一个柱子-》放入栈中
stack.push(i);
}
while(height[i] >= height[stack.peek()]){
int low = stack.pop();
if (stack.isEmpty()) break;
int dis = i - stack.peek() -1;
res += (Math.min(height[i],height[stack.peek()])-height[low]) * dis;
}
stack.push(i);
}
return res;
}
}
比较左右大小都可以用单调栈,如果求右边比他大的,栈单调递增
class Solution {
public int largestRectangleArea(int[] heights) {
//数组扩容
int[] h = new int[heights.length +2];
h[0] = 0;
h[h.length-1]=0;
for(int i = 1;i<=heights.length;i++){
h[i] = heights[i-1];
}
int res = 0;
if (heights.length < 1) return res;
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
for(int i = 1 ;i<h.length;i++){
if(h[i] >= h[stack.peek()]){
//如果栈为空,或当前柱子大于上一个柱子-》放入栈中,栈中单增
stack.push(i);
}
while(!stack.isEmpty() && h[i] < h[stack.peek()]){
int mid = stack.pop();
int left = stack.peek();
int dis = i - left -1;
res = Math.max(res, h[mid] * dis);
}
stack.push(i);
}
return res;
}
}