publicclassTrappingRainWaterLeetcode42{publicstaticvoidmain(String[] args){System.out.println(trap(newint[]{0,1,0,2,1,0,1,3,2,1,2,1}));// 6System.out.println(trap(newint[]{4,2,0,3,2,5}));// 9}recordData(int height,int i){}staticinttrap(int[] heights){int sum =0;LinkedList<Data> stack =newLinkedList<>();for(int i =0; i < heights.length; i++){Data right =newData(heights[i], i);while(!stack.isEmpty()&& stack.peek().height < heights[i]){Data pop = stack.pop();Data left = stack.peek();if(left !=null){
sum +=(Integer.min(left.height, right.height)- pop.height)*(right.i - left.i -1);}}
stack.push(right);}return sum;}}
维护一个单调栈
当加入新柱子(right)时,如果发现要弹出之前的柱子,表示遇到了凹陷的地方
此时栈里没有更左边的柱子,表示拦不住雨水
栈里有左边柱子(left)就可以计算雨水容量:
(
r
i
g
h
t
.
i
−
l
e
f
t
.
i
−
1
)
∗
M
i
n
(
r
i
g
h
t
.
h
e
i
g
h
t
,
l
e
f
t
.
h
e
i
g
h
t
)
−
p
o
p
.
h
e
i
g
h
t
(right.i - left.i-1)*Min(right.height,left.height)-pop.height
(right.i−left.i−1)∗Min(right.height,left.height)−pop.height