42. Trapping Rain Water
难度:Hard
刷题内容
原题连接
- https://leetcode.com/problems/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.
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
��¼ l = 0内容描述������飬��� height[i] < height[l],��˵����λ������ˮ����¼����ˮ内容描述�� height[i] >= height[l]����˵��[i,l]�������ڿ��Ի�ˮ��Ȼ���ȥ����ˮ内容描述ǻ�ˮ内容描述内容描述�֮����� l != height.size() - 1内容描述����飬内容描述���衣
˼· **- ʱ�临�Ӷ�: O(N)*- �ռ临�Ӷ�: O(1)***
class Solution {
public:
int trap(vector<int>& height) {
int l = 0,sum1 = 0,water = 0,i;
for(i = 1;i < height.size();++i)
if(height[i] >= height[l])
{
water = water + height[l] * (i - l - 1) - sum1;
l = i;
sum1 = 0;
}
else
sum1 += height[i];
if(l != (height.size() - 1))
{
int temp = l;
sum1 = 0;
for(i = height.size() - 2,l = height.size() - 1;i >= temp;--i)
if(height[i] >= height[l])
{
water = water + height[l] * (l- i - 1) - sum1;
l = i;
sum1 = 0;
}
else
sum1 += height[i];
}
return water;
}
};