leetcode:#42. 接雨水
采用Java实现,构建一个单调递增栈。
class Solution {
public int trap(int[] height) {
Stack<Integer> stack = new Stack<>();
int result = 0;
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
Integer topIndex = stack.pop();
if (stack.isEmpty()) {
break;
}
Integer leftColumnIndex = stack.peek();
int distance = i - leftColumnIndex - 1; // 凹下去的宽度
int boundedHeight = Math.min(height[i], height[leftColumnIndex]) - height[topIndex]; // 凹下去的高度
result = result + distance * boundedHeight;
}
stack.push(i);
}
return result;
}
}