42.Trapping Rain Water

来源:互联网 发布:淘宝网汉服女装 编辑:程序博客网 时间:2024/05/17 05:53

思路:这个算最大储水量的。用栈。找到第一个峰值入栈,然后往后遍历:“如果小于该峰值就入栈,直到当前值比峰值大,就可以开始出栈并同时计算储水”,然后更新峰值,继续重复这个操作直到vector遍历完。注意:如果最后是递减的,即最后一个vector元素不是峰值,那么就得特殊处理了。时间复杂度O(n)

代码:

class Solution {

public:
    int trap(vector<int>& height) {
        int len=height.size();
        if(len<=1) return 0;
        stack<int> my_stack;
        int most_height;
        int result=0;
        //init
        int k;
        for(int i=1;i<len;++i){
            if(height[i]<height[i-1]){
                k=i-1;
                my_stack.push(height[k]);
                most_height=height[k];
                break;
            }

        }

        if(my_stack.empty()) return 0;
        //process
        for(int i=k;i<len;++i){
            if(height[i]<most_height){
                my_stack.push(height[i]);
            }else{
                while(!my_stack.empty()){
                    result+=most_height-my_stack.top();
                    my_stack.pop();
                }
                //更新
                my_stack.push(height[i]);
                most_height=height[i];
            }
        }
        //如果最后一个元素小于当前的most_height,特殊处理
        int second_height=my_stack.top();
        my_stack.pop();
        while(!my_stack.empty()){
            int cur=my_stack.top();
            if(cur<second_height){
                result+=second_height-cur;   
            }else{
                second_height=cur;
            }
            my_stack.pop();
            
        }
        return result;
    }
};
0 0
原创粉丝点击