接雨水(LeetCode)
单调栈问题
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
来源:力扣(LeetCode)
提示:
n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105
题解
//该解法是将元素的下标入栈
class Solution {
public int trap(int[] height) {
if(height.length == 0)return 0;
int ans = 0;
Stack<Integer> stack = new Stack();
for(int i=0;i<height.length;i++){
//当栈不为空并且即将入栈的元素高度大于栈顶元素的高度
while(!stack.isEmpty() && height[stack.peek()] < height[i]){
//获取栈顶元素的下标,并将栈顶元素弹出
int topIdx = stack.pop();
//获取下一个元素的下标,上次弹出元素之后可能会报空指针异常
int nextIdx = stack.isEmpty()==true ? topIdx : stack.peek();
//计算宽度
int widthh = i - nextIdx - 1;
//计算高度
int heightt = Math.min(height[i],height[nextIdx])-height[topIdx];
//计算面积
ans += widthh*heightt;
}
//入栈
stack.push(i);
}
return ans;
}
}