class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int maxheight = 0, ret = 0;
vector<int> container(n,0);
for(int i=0; i<n; i++){
container[i] = maxheight;
maxheight = max(height[i], maxheight); //算每个bar左边最大高度啊
}
maxheight = 0;
for(int i = n-1; i>=0; i--){
container[i] = min(maxheight, container[i]); //这里的maxheight其实就是每个bar的右边最大高度,左右两边去最小盛水
maxheight = max(height[i], maxheight); //算每个bar左边最大高度啊
ret += container[i]-height[i] > 0 ? container[i] - height[i] : 0; //这个bar下能否盛水
}
return ret;
}
};
leetcode42+Trapping Rain Water+双指针
最新推荐文章于 2024-11-02 15:25:13 发布