Leetcode 42 Trapping Rain Water

来源:互联网 发布:js作用域链 编辑:程序博客网 时间:2024/05/17 01:48

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;    }}