leetcode 42. Trapping Rain Water

来源:互联网 发布:淘宝怎么看买家秀 编辑:程序博客网 时间:2024/06/07 01:26

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!

Subscribe to see which companies asked this question.

这道题看起来挺难解决,其实想通其中的逻辑,还是很简单的。

每个水槽的存水量等于左边最高的长度和右边最高的长度的最小值减去自身的长度。把所有的水槽的值加起来即可。

public class Solution {    public int trap(int[] height) {        if(height.length<3)return 0;        int[]left = new int[height.length];        int[]right = new int[height.length];        left[0] = height[0];        right[height.length-1] = height[height.length-1];        int max = left[0];        for(int i=1;i<height.length;i++){            left[i] = Math.max(height[i],max);            max = Math.max(max,height[i]);        }        max = right[height.length-1];        for(int j=height.length-2;j>=0;j--){            right[j] = Math.max(height[j],max);            max = Math.max(height[j],max);        }        int count = 0;        for(int i=1;i<height.length-1;i++){            count += Math.min(left[i],right[i]) - height[i];        }        return count;    }}


原创粉丝点击