Last updated
Was this helpful?
Last updated
Was this helpful?
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
.
(1) Two Pointers
(2) Monotone Stack
思路:(1) 凹陷处可以积水。所以寻找先递减后递增的位置就可以了
(2) 维护一个单调递减的Stack,当heights[stack.peek()] <= heights[i], 找到凹陷处,出栈,计算可蓄水的体积
(3) 计算体积时,以bottomIndex作为中点,向两边找出比它高的bar(corner case: 如果此时stack为空,则无法找到左边的bar)
Two Pointers: 时间复杂度O(n), 空间复杂度O(1)
Monotone Stack: 时间复杂度O(n), 空间复杂度O(n)