42. Trapping Rain Water
对于这题我只能说,好好看好好学。
初看题目也有想到用堆栈,但对于写法却一头雾水。
class Solution {
public:
int trap(vector<int>& height) {
stack<int> hIdx;
int i = 0, h = 0, res = 0;
while (i<height.size()){
if (hIdx.empty() || height[i]<=height[hIdx.top()]) {
hIdx.push(i++);
} else {
h = height[hIdx.top()];
hIdx.pop();
if(hIdx.empty()) continue;
res += (min(height[hIdx.top()],height[i])-h) * (i-hIdx.top()-1);
}
}
return res;
}
};