【leetcode字节跳动题库】42. Trapping Rain Water
作者:互联网
用个单调栈
提交代码
class Solution {
public int trap(int[] height) {
Stack<Integer> hStack=new Stack<Integer>();
Stack<Integer> pStack=new Stack<Integer>();
int hLeft=0,base=0,water=0;
for(int i=0;i<height.length;i++) {
if(hStack.isEmpty()||hStack.peek()>height[i]) {
hStack.push(height[i]);
pStack.push(i);
}else {
while(!hStack.isEmpty()&&hStack.peek()<=height[i]) {
base=hStack.pop();
pStack.pop();
if(hStack.isEmpty()) break;
hLeft=hStack.peek();
water+=(Math.min(hLeft, height[i])-base)*(i-pStack.peek()-1);
}
hStack.push(height[i]);
pStack.push(i);
}
}
return water;
}
}
运行结果
AXIMI 发布了390 篇原创文章 · 获赞 27 · 访问量 7万+ 私信 关注标签:Trapping,hStack,int,42,Rain,height,pStack,new,Stack 来源: https://blog.csdn.net/AXIMI/article/details/104521477