美文网首页
42. Trapping Rain Water

42. Trapping Rain Water

作者: GoDeep | 来源:发表于2018-08-03 21:35 被阅读0次
image.png
package l42;
class Solution {
    public int trap(int[] a) {
        int p=0, q=a.length-1;
        int res=0;
        // 需要额外维护左右2边到目前为止的max
        int maxLeft=0, maxRight=0;
        while(p<q) {
            if(a[p]>a[q]) {
                res+=Math.max(0, maxRight-a[q]);
                maxRight=Math.max(maxRight, a[q]);
                q--;
            } else {
                res+=Math.max(0, maxLeft-a[p]);
                maxLeft=Math.max(maxLeft, a[p]);
                p++;
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        Solution s=new Solution();
        System.out.println(s.trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1}));
    }
}

相关文章

网友评论

      本文标题:42. Trapping Rain Water

      本文链接:https://www.haomeiwen.com/subject/dlouvftx.html