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

Leetcode 42 Trapping Rain Water

2017-05-22 15:38 429 查看
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
.



双指针的问题啊,重点在于,怎么判断当前能够存住水。

思考一下,存住的水取决于左右两块板的高度,首先要都大于零,并且受短板的牵制。

plank就相当于从两侧开始造一个木桶,plank的大小就是高度,只增不减,遇到比plank矮的就能储水

如果继续遇到新的plank就更新plank的值

public class Solution {
public int trap(int[] A) {
int i = 0, j = A.length - 1, result = 0, plank = 0;
while(i <= j){
plank = plank < Math.min(A[i], A[j]) ? Math.min(A[i], A[j]) : plank;
result = A[i] >= A[j] ? result + (plank - A[j--]) : result + (plank - A[i++]);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: