这里用了双指针法
一个点水量取决于其左边最大值和右边最大值中的较小者,每次移动left和right中较小的那个就可以。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int leftmax = 0;
int rightmax = 0;
int water = 0;
while (left < right) {
leftmax = max(height[left], leftmax);
rightmax = max(height[right], rightmax);
if (height[left] < height[right]) {
water = water + leftmax - height[left];
left++;
}
else {
water = water + rightmax - height[right];
right--;
}
}
return water;
}
};
int main(){
Solution test;
vector<int>height = { 0,1,0,2,1,0,1,3,2,1,2,1 };
cout << test.trap(height);
}