#include <vector> #include <iostream> using namespace std; class Solution { public: int trap(vector<int>& height) { int len=height.size(); //当前位置左边界最大值 int left[len]; //当前位置右边界最大值 int right[len]; left[0]=height[0]; right[len-1]=height[len-1]; int res=0; for (int i = 1; i < len; i++) { left[i]=max(left[i-1],height[i]); right[len-1-i]=max(right[len-i],height[len-1-i]); } //左右边界最小值与当前位置高度的差,即为当前可存储的雨水 for (int i = 0; i < len; i++) { int temp=min(left[i],right[i]); if (temp-height[i]>0) { res+=temp-height[i]; } } return res; } }; int main(){ Solution s; vector<int> height={0,1,0,2,1,0,1,3,2,1,2,1}; cout<<s.trap(height); return 0; }
标签:right,int,res,42,len,height,雨水,left From: https://www.cnblogs.com/Yshun/p/16953632.html