【柱形图】Trapping Rain Water

来源:互联网 发布:淘宝助理教程视频 编辑:程序博客网 时间:2024/05/15 23:53

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!


解法:选取最大值作为中间立柱,分别从两头求取存水量;用curMax记录当前左或右边的最大高度,因为有中间立柱挡住肯定能存水,curMax-A[i]则为存水量

参考:http://www.cnblogs.com/lichen782/p/Leetcode_Trapping_Rain_Water.html


public class Solution {    public int trap(int[] A) {        int len = A.length;        if(len <= 2) return 0;                int water = 0;        int curMax = 0;        int mid = 0;                for(int i=0; i<len; i++){            if(A[mid] < A[i]) mid = i;        }                curMax = 0;        for(int i=0; i<=mid; i++){            if(A[i] > curMax) curMax = A[i];            else water += curMax - A[i];        }                curMax = 0;        for(int i=len-1; i>=mid; i--){            if(A[i] > curMax) curMax = A[i];            else water += curMax - A[i];        }        return water;    }}


解法:选取最大值作为中间立柱,分别从两头求取存水量

参考:http://www.cnblogs.com/lichen782/p/Leetcode_Trapping_Rain_Water.html

0 0
原创粉丝点击