Hard 42题 Trapping Rain Water

来源:互联网 发布:mac文件存放在哪里 编辑:程序博客网 时间:2024/05/01 22:10

Question:

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!


Solution:

public class Solution {    public int trap(int[] height) {        int secHeight=0;        int left=0;        int right=height.length-1;        int area=0;        while(left<right)        {            while(left<right && height[left]<=height[right])            {                secHeight=Math.max(secHeight,height[left]);                area+=secHeight-height[left];                left++;            }            while(left<right && height[left]>height[right])            {                secHeight=Math.max(secHeight,height[right]);                area+=secHeight-height[right];                right--;            }        }        return area;    }}




0 0
原创粉丝点击