Leetcode: trapping-rain-water

来源:互联网 发布:mac 建立文件夹 编辑:程序博客网 时间:2024/06/05 19:03

题目:

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!


思路:

1.遍历数组,找出最大值的下标;

2.分别从左右向中间遍历;

3.设置left=0,right=0;分别表示遍历过程中出现的最大值

4.若left>A[i](right>A[i]),说明当前是洼地,累加面积


代码:

public class Solution {    public int trap(int[] A) {                int max=0;        int left=0;        int right=0;                for(int i=0; i<A.length; i++)        {            if(A[i] > A[max])                max = i;        }                int sum = 0;        for(int i=0; i<max;i++)        {            if(A[i]>=left)            left=A[i];            else                sum+= left-A[i];        }                for(int i=A.length-1; i>max;i--)        {            if(A[i]>=right)            right=A[i];            else                sum+= right-A[i];        }        return sum;    }}


1 0