Trapping Rain Water

来源:互联网 发布:淘宝小号注册机源码 编辑:程序博客网 时间:2024/06/05 06:30

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!

思路:首先找到 最高点, 然后分别从左向右 和 从右向左 来向 最高点遍历, 并设置一个水平面。 如果 A[i] 比 floor  低的话, 就可以积水, 就把积水加上, 如果 A[i] 比 floor 多的话, 就把 floor 更新成A[I]

易错点: 从左向 最高点遍历完, 一定要 把floor  重置为0 , 因为 左右的 水平面 是被 最高点分割的。

public class Solution {    public int trap(int[] A) {        if(A.length < 1)            return 0;        int water = 0;        int highest = 0;        int highIndex = 0;        //Find the highest point;        for(int i = 0; i < A.length; i++){            if(A[i] > highest){                highest = A[i];                highIndex = i;            }        }        int floor = 0;        //Traverse from 0 to HighIndex        for(int i = 0; i < highIndex; i++){            if(floor > A[i]){                water += floor - A[i];            }else{                floor = A[i];            }        }        //Traverse from n - 1 to highIndex        floor = 0;// -----        for(int i = A.length - 1; i > highIndex; i--){            if(floor > A[i]){                water += floor - A[i];            }else{                floor = A[i];            }        }        return water;    }}



0 0
原创粉丝点击