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

LeetCode - Trapping Rain Water 等雨水的凹槽容量

2014-07-07 14:35 756 查看
作者:disappearedgod

文章出处:http://blog.csdn.net/disappearedgod/article/details/37510665

时间:2014-7-7

题目


Trapping Rain Water

Total Accepted: 11100 Total
Submissions: 39417My Submissions

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!

解法

解法一:

靖心的博客中已经详细分析了这道题的意思。

我的想法是:

数学解法是先算一个规则图形(凸包图形),然后再在图形上减去这个已有数组的值。

进一步想一下:我们的凸包只是长方形,而不可能计算梯形面积,而长方形其实是在“宽”的基础上对长的积分而已;而积分的同时可以进一步做减法。

public class Solution {
public int trap(int[] A) {
int Height = 0;
int left = 0;
int right = A.length - 1;
int area = 0;
while(left < right){
if(A[left] < A[right]){
Height = Math.max(Height,A[left]);
area +=Height - A[left];
left++;
}
else{
Height = Math.max(Height,A[right]);
area += Height - A[right];
right--;
}
}
return area;
}
}


参考

【1】LeetCode
Trapping Rain Water等雨水的凹槽容量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: