您的位置:首页 > 移动开发

LeetCode 42 - Trapping Rain Water

2016-03-03 12:36 513 查看

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!

My Two Pass Code

class Solution {
public:
int trap(vector<int>& height) {
int size = height.size();
int start = 0, end = size - 1;
int total = 0;

// Left to right
for (int i = 1; i < size; i++)
{
if (height[i] >= height[start])
{
if (i == start + 1)
start= i;
else
{
end = i;
// Caculate
int s = min(height[start], height[end]) * (end - start - 1);
cout << start << " " << end << " " << s << endl;
for (int j = start + 1; j < end; j++)
s -= height[j];
total += s;

start = end;
}
}
}

// Right to left
start = size - 1, end = 0;
for (int i = size - 2; i >= 0; i--)
{
if (height[i] > height[start])
{
if (i == start - 1)
start= i;
else
{
end = i;
// Caculate
int s = min(height[start], height[end]) * (start - end - 1);
for (int j = start - 1; j > end; j--)
s -= height[j];
total += s;

start = end;
}
}
}

return total;
}
};


Runtime: 20 ms



My One Pass Code

class Solution {
public:
int trap(vector<int>& height) {
int size = height.size();
int start = 0, end = size - 1;
int max_left_height = 0, max_right_height = 0;
int total = 0;

while (start <= end)
{
if (height[start] <= height[end])
{
if (height[start] <= max_left_height)
total += max_left_height - height[start];
else
max_left_height = height[start];
start++;
}
else
{
if (height[end] <= max_right_height)
total += max_right_height - height[end];
else
max_right_height = height[end];
end--;
}
}

return total;
}
};
Runtime: 8 ms

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: