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;
    }
};

 

posted @ 2022-02-22 17:33  jozon  阅读(38)  评论(0)    收藏  举报