42. Trapping Rain Water
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.public int trapRainWater(int[] heights) {
Stack<Integer> stack = new Stack<>();
int i = 0, res = 0;
while (i < heights.length) {
if (stack.isEmpty() || heights[i] <= heights[stack.peek()]) {
stack.push(i);
i++;
} else {
int bottom = stack.pop();
if (stack.isEmpty()) continue;
// 注意这里left是不pop出来的,因为可以继续形成坑
int left = stack.peek();
// System.out.println("poped bottom = " + bottom + "; left = " + left + "; right = " + i);
int h = Math.min(heights[i], heights[left]) - heights[bottom], w = i - left - 1;
int water = h * w;
// System.out.println("water is " + water);
res += water;
// 注意这里是不进行i++的,因为还要继续判断当前的位置是不是还能继续形成坑
}
}
return res;
}aLast updated




