42 Trapping Rain Water
Last updated
Last updated
Givennnon-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1]
, return6
.
The above elevation map 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.
思路:
(1) 凹陷处可以积水。所以寻找先递减后递增的位置就可以了
(2) 维护一个单调递减的Stack,当heights[stack.peek()] <= heights[i], 找到凹陷处,出栈,计算可蓄水的体积
(3) 计算体积时,以bottomIndex作为中点,向两边找出比它高的bar(corner case: 如果此时stack为空,则无法找到左边的bar)
时间和空间都是O(n)