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!
分析
空间复杂度O(n)
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以
1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
2. 从右往左扫描一遍,对于每个柱子,求最大右值;
3. 再扫描一遍,把每个柱子的面积并累加。
class Solution {public:int trap(vector<int>& height) {int length=height.size();int *max_left=new int[length]();int *max_right=new int[length]();for(int i=1;i<length;i++){max_left[i]=max(max_left[i-1],height[i-1]);max_right[length-i-1]=max(max_right[length-i],height[length-i]);}int sum=0;for (int i=0;i<length;i++){int h=min(max_left[i],max_right[i]);if(h>height[i])sum+=h-height[i];}delete[]max_left;delete[]max_right;return sum;}};
也可以,该方法空间复杂度O(1)
1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
2. 处理左边一半;
3. 处理右边一半。
class Solution {public:int trap(vector<int>& height) {int max = 0; // 最高的柱子,将数组分为两半int n=height.size();for (int i = 0; i < n; i++)if (height[i] > height[max]) max = i;int water = 0;for (int i=0,peak=0;i<max;i++){if(peak<height[i])peak=height[i];elsewater+=peak-height[i];}for(int j=n-1,peak=0;j>max;j--){if(peak<height[j])peak=height[j];elsewater+=peak-height[j];}return water;}};
浙公网安备 33010602011771号