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

LeetCode Trapping Rain Water

2015-06-06 13:27 357 查看

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!
题意:给出n个非负整数,表示水平高度,求下雨后存取了多少水
思路:在计算一个点能够容纳多少水,与它cur左边的最大值leftMax和右边的最大值rightMax有关,则该点能够容纳的水为min(leftMax, rightMax) - cur;另外一种思路时从两边搜索,总是从较小的一边开始
代码如下
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> left(n), right(n);

if (n > 0) {
left[0] = height[0];
right[n - 1] = height[n - 1];
}

for (int i = 1; i < n; i++) {
left[i] = max(left[i - 1], height[i]);
right[n - 1 - i] = max(right[n - i], height[n - 1 - i]);
}

int ans = 0;
for (int i = 0; i < n; i++) {
int tmp = min(left[i], right[i]) - height[i];
if (tmp > 0) ans += tmp;
}

return ans;
}
};

思路2代码如下
public class Solution {
public int trap(int[] height)
{
int n = height.length;
int ans = 0;
int tmp = 0;
int left = 0, right = n - 1;
while (left < right) {
if (height[left] < height[right]) {
tmp = Math.max(height[left], tmp);
ans += tmp - height[left];
left++;
} else {
tmp = Math.max(height[right], tmp);
ans += tmp - height[right];
right--;
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: