中间低,两边高才有雨水,想到单减栈
cur>=height[top]低:push
cur<height[top]:此时站内应至少有两个元素才能形成坑
class Solution {
public int trap(int[] height) {
Stack<Integer> stack = new Stack<>();
int i = 0, res = 0;
while (i < height.length) {
if (stack.isEmpty() || height[i] <= height[stack.peek()]) {
stack.push(i++);
} else {// 栈至少有两个元素
int top = stack.pop();
if (stack.isEmpty())
continue;
res += (Math.min(height[stack.peek()], height[i]) - height[top]) * (i - stack.peek() - 1);
}
}
return res;
}
}