LeetCode-042-接雨水

思路:这里使用单调递减栈的做法,写起来简单些
代码:
class Solution {
public int trap(int[] height) {
Stack<Integer> st=new Stack<>();//单调栈,存储单调递减的墙
int current=0;//右边的墙
int sum=0;//总雨量
while(current<height.length){
//判断左墙是否存在以及右墙大于左墙
while(!st.isEmpty()&&height[current]>height[st.peek()]){
//底部高度为h,弹出栈顶
int h=height[st.pop()];
//如果栈空,说明两墙无间隙,直接break
if(st.isEmpty())break;
//取短墙
int min=Math.min(height[current],height[st.peek()]);
//计算宽度
int w=current-st.peek()-1;
//计算雨量
sum+=w*(min-h);
}
//否则,直接入栈
st.push(current);
//移动指针
current++;
}
return sum;
}
}
LeetCode 042:动态规划解决接雨水问题
本文介绍了一种使用单调栈解决LeetCode题目042接雨水问题的算法。通过单调递减栈存储高度,动态判断左右墙高度并计算可收集的雨水量,实现高效求解。
439

被折叠的 条评论
为什么被折叠?



