给出 n 个非负整数,代表一张X轴上每个区域宽度为 1 的海拔图, 计算这个海拔图最多能接住多少(面积)雨水。
样例
样例 1:
输入: [0,1,0]
输出: 0
样例 2:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
挑战
O(n) 时间, O(1) 空间
O(n) 时间, O(n) 空间也可以接受
思路:两边往中间最高的板块聚集,就可以只考虑成同一种情况。
找到当前左边最大的板块,和当前板块进行比较,若当前板块小,则说明可以盛最大板块减去当前板块雨水,否则,最大板块替换为当前板块,而先前计算出来的雨水量决定于前面的最大板块,与替换后的最大板块无关。对于右边开始的同理可得
class Solution {
public:
/**
* @param heights: a list of integers
* @return: a integer
*/
int trapRainWater(vector<int> &heights) {
// write your code here
if(heights.size()<=2) return 0;
int left_max=0;
int right_max=0;
int left_index=0;
int right_index=heights.size()-1;
int res=0;
while(left_index!=right_index)
{
if(heights[left_index]<=heights[right_index])
{
if(heights[left_index]<=left_max)
{
res+=left_max-heights[left_index++];
}
else
{
left_max=heights[left_index++];
}
}
else
{
if(heights[right_index]<=right_max)
{
res+=right_max-heights[right_index--];
}
else
{
right_max=heights[right_index--];
}
}
}
return res;
}
};