42 Trapping Rain Water
原题
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!
分析
- 两个当前最高值中的较低值问题
方法
-
从左边遍历,算出目前最高值,用vector保存,再从右边遍历,得到另一组目前最高值,比较两组最高值中的较低值,得到的最终vector就是积满雨水的数组。
-
用两个指针从两边分别开始遍历,值小的指针向中间移动1(两个指针在最高值相遇,并停止遍历),如果该较小值,比下个数更大,就能乘雨水。
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1, level = 0, res = 0;
while (l < r) {
int lower = height[(height[l] < height[r]) ? l++ : r--];//两个高值中的较低值
level = max(level, lower);//level:积满雨水后的高度
res += level - lower;
}
return res;
}
- 使用栈(Stack),从0遍历,下坡则入栈,移位,上坡则出栈,计算,栈不为空继续计算,每次计算都把栈顶推出,栈为空则入栈,继续遍历。把栈顶元素取出来当作坑,新的栈顶元素就是左边界,当前高度是右边界,只要取二者较小的,减去坑的高度,长度就是右边界坐标减去左边界坐标再减1,二者相乘就是盛水量啦。
int trap(vector<int>& height) {
stack<int> st;
int i = 0, res = 0, n = height.size();
while (i < n) {
if (st.empty() || height[i] <= height[st.top()]) //
{
st.push(i++);
} else {
int t = st.top(); st.pop();
if (st.empty()) continue;
res += (min(height[i], height[st.top()]) - height[t]) * (i - st.top() - 1);
}
}
return res;
}