class Solution {
public:
int trap(vector<int>& height) {
stack<int> S;
int ans = 0;
int last_height = 0;
for(int ii = 0; ii < height.size(); ii++) {
while(!S.empty() && height[ii] > height[S.top()]) {
int h = min(last_height, height[ii]) - height[S.top()];
int jj = S.top();
S.pop();
int kk = jj - 1;
if(!S.empty()) kk = S.top();
ans += h * (jj - kk);
}
if(S.empty()) last_height = height[ii];
S.push(ii);
}
return ans;
}
};
【leetcode 单调栈 C++】42. Trapping Rain Water
最新推荐文章于 2024-07-14 11:23:58 发布