贪心思想,从两边往中间扫,高度小的边移动:
class Solution {
public:
int trap(vector<int>& height) {
int N = height.size();
int maxL,maxR;
int L,R;
L = maxL = maxR = 0;
R = N-1;
int ans = 0;
while(L<R){
maxL = max(maxL,height[L]);
maxR = max(maxR,height[R]);
if(maxL < maxR){
ans += max(0,maxL - height[L]);
L++;
}else{
ans += max(0,maxR - height[R]);
R--;
}
}
return ans;
}
};