42. 接雨水


超时的代码如下,主要思路是使用堆栈存储每个柱子的高度,然后用每一层减去上一个该高度所在位置
思路没问题就是超时了
class Solution {
public:
int trap(vector<int>& height) {
int m =0;
int l = height.size();
int result = 0;
for(int i=0;i<l;i++){
m=max(m,height[i]);
}
vector<stack<int>>temp(m+1);
for(int i=0;i<l;i++){
for(int j=1;j<=height[i];j++){
temp[j].push(i);
}
}
for(int i=1;i<=m;i++){
while(temp[i].size()>1){
int temp_top = temp[i].top();
temp[i].pop();
result+=temp_top-temp[i].top()-1;
}
}
return result;
}
};

浙公网安备 33010602011771号