42. Trapping Rain Water

来源:互联网 发布:linux ddos攻击脚本 编辑:程序博客网 时间:2024/05/17 04:34

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.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.Thanks Marcos for contributing this image!


看图即可知道要做什么系列。

我的实现是分两种情况考虑,分别是高度上升和下降这两种情况。用一个栈辅助。下降的时候用栈保存好位置和相应的高度。上升的时候,循环知道栈空,读取栈的信息,把比当前高度低的都出栈,并且更新结果res,遇到比当前高度高的就退出循环,然后将当前bar的位置和高度入栈。具体实现见代码。


代码:

class Solution {public:int trap(vector<int>& height) {int res = 0, i, n = height.size();stack<bar>sta;if(n <= 1) return 0;int line = 0;sta.push(bar(0, height[0]));for(i=1; i<n; ++i){if(height[i] < height[i-1]){sta.push(bar(i, height[i]));line = height[i];}else{bar tmp;while(!sta.empty()){tmp = sta.top();if(tmp.h > height[i]){res += (height[i] - line) * (i - tmp.pos - 1);line = height[i];break;}else{res += (tmp.h - line) * (i - tmp.pos - 1);line = tmp.h;sta.pop();}}sta.push(bar(i, height[i]));}}return res;}private:struct bar{int pos;int h;bar(): pos(0),h(0) {}bar(int n,int m): pos(n),h(m) {}};};


0 0
原创粉丝点击