class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int left = 0, right = n - 1;
int lmax = 0, rmax = 0;
int res = 0;
while (left < right) {
if (height[left] < height[right]) {
lmax = max(lmax, height[left]);
res += lmax - height[left++];
}
else {
rmax = max(rmax, height[right]);
res += rmax - height[right--];
}
}
return res;
}
};
用什么:Two Pointers
为什么:通过lmax与rmax可知道能“捆住”的雨量,从而计算总雨量
思路:两边往中间走,height小的优先,得到当前为止左或右的最大高度,然后往res里加左或右的max高度与当前高度的差
注意之处:左边和右边两个领域需要完全分开,避免混乱
时间:O(N)
空间:O(1)