解法一:
先求出从左到右的最大值保存在数组right中,每一个元素的接水量就等于min(left,right)减去当前的值,循环一遍就能就出总接水量了。
class Solution {
public:
/**
* @param heights: a vector of integers
* @return: a integer
*/
int trapRainWater(vector<int> &heights) {
// write your code here
int size = heights.size();
if(size == 0)
return 0;
int *right = new int[size]; // 保存从左到右的最大值
int temp = heights[size-1];
for(int i = size-1; i >= 0; i--)
{
if(temp < heights[i])
{
right[i] = heights[i];
temp = heights[i];
}
else
{
right[i] = temp;
}
}
int left = 0; // 记录左边最大值
int sum = 0;
for(int i = 0; i < size; i++)
{
if(left < heights[i])
left = heights[i];
sum += max(min(left, right[i])-heights[i], 0);
}
delete[] right;
return sum;
}
int min(int a, int b)
{
if(a > b)
return b;
else
return a;
}
int max(int a, int b)
{
if(a > b)
return a;
else
return b;
}
};
解法二:
可以用两个指针分别指向头和尾,判断每个元素的接水量的瓶颈在于左右两边最大值中的更小的那一个。
注while循环 需加自加 在计算, 不然到达条件后就漏掉一次循环了
class Solution {
public:
/**
* @param heights: a vector of integers
* @return: a integer
*/
int trapRainWater(vector<int> &heights) {
// write your code here
if(heights.empty())
return 0;
int left;
int right;
int sum = 0;
vector<int>::iterator itL, itR;
itL = heights.begin();
itR = --heights.end();
left = *itL;
right = *itR;
while(itL != itR)
{
if(left < right)
{
itL++;
sum += max(left - *itL, 0);
left = max(*itL, left);
}
else
{
itR--;
sum += max(right - *itR, 0);
right = max(*itR, right);
}
}
return sum;
}
int max(int a, int b)
{
if(a > b)
return a;
else
return b;
}
};