lintcode[363]:接雨水

来源:互联网 发布:学习辅助软件 编辑:程序博客网 时间:2024/05/16 19:37

描述:Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
样例
海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.
思路:
开始想到直方图内最大矩形面积,那么直接套用,发现不是那样的,这道题,如果对于任意一个vector内的值,在其两侧存在比它海拔高的值,那么,这个地方就会存水(注意必须是两边同时存在比它高的值才行),存水的量则取决于两边比他高的值中较小那个(类似于木桶短板效应)。那么我们只需要从左往右遍历一遍得到左边比它大的值之中的最大值,从右向左遍历得到右边比它大的值之中的最大值,在遍历一遍求得面积即可(当然,分析到这,感觉很亲切:因为又可以用栈了,哈哈)。
参考代码:

int trapRainWater(vector<int> &heights) {        int len = heights.size();        stack<int> stack_;        vector<int> left(len);        vector<int> right(len);        int ans = 0;        for(int i = 0; i < len; i ++){            if(stack_.empty()){                stack_.push(heights[i]);                left[i] = 0;            }else{                if(heights[i] < stack_.top()){                    left[i] = stack_.top() - heights[i];                }else{                    stack_.push(heights[i]);                    left[i] = 0;                }            }        }        while(!stack_.empty()){            stack_.pop();        }        for(int i = len - 1; i >= 0; i --){            if(stack_.empty()){                stack_.push(heights[i]);                right[i] = 0;            }else{                if(heights[i] < stack_.top()){                    right[i] = stack_.top() - heights[i];                }else{                    stack_.push(heights[i]);                    right[i] = 0;                }            }        }        for(int i = 0; i < len; i ++){            if(left[i] && right[i]){                int temp = left[i] > right[i] ? right[i] : left[i];                ans += temp;            }        }        return ans;    }

同时附上自己写的超时代吗,以上的分析就是从这里来的,如果觉得上面的代码难以理解,下面的思想是一样的,就是循环时间超时了。

int trapRainWater(vector<int> &heights) {        // write your code here        int len = heights.size();        int ans = 0;        for(int i = 0; i < len; i ++){            int l = i;            int r = i;            int max1 = heights[i];            int max2 = heights[i];            while(--l >= 0){                if(heights[l] > max1){                    max1 = heights[l];                }            }            while(++r < len){                if(heights[r] > max2){                    max2 = heights[r];                }            }            if(max1 > heights[i] && max2 > heights[i]){                int temp = max1 > max2 ? max2 : max1;                ans += temp - heights[i];            }        }        return ans;    }