注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解
题目: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.
解析:
1:扫描数组,找到最高的柱子,这个柱子将数组分成两半;
2:扫描左边的一半,找到每根柱子左边的最大值,然后每根柱子能够容纳的水量为 max_left - height;
3:扫描右边的一半,找到每根柱子右边的最大值,然后每根柱子能够容纳的水量为 max_right - height;
代码如下:
/时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int trap(const vector<int>& A) {
const int n = A.size();
int max = 0; // 最高的柱子的指标
for (int i = 0; i != n; ++i)
if (A[max] < A[i]) max = i;
int water = 0;
//在[0, max)区间内柱子其左边高度最大值;
for (int i = 0, peak = 0; i != max; ++i)
if (A[i] > peak) peak = A[i];
else water += peak - A[i];
//在[max + 1, n)区间内柱子其右边高度最大值
for (int i = n - 1, top = 0; i != max; --i)
if (A[i] > top) top = A[i];
else water += top - A[i];
return water;
}
};