42. Trapping Rain Water

来源:互联网 发布:dnf固伤技能谁数据最高 编辑:程序博客网 时间:2024/05/16 15:18

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.
这里写图片描述

先找出数组最大值maxindex,讲数组分为0~maxindex,maxindex~n-1两组。对于第一组,右界确定,只要当前A[i]小于其左边的最大值就可以盛水;对于第二组,左界确定,只要当前A[i]小于其右边的最大值就可以盛水。

public class Solution {    public int trap(int[] A) {        int n = A.length;          if(n <= 2) return 0;        int max = -1, maxInd = 0;        int i = 0;        for(; i < n; ++i){              //找出最大值            if(A[i] > max){                max = A[i];                maxInd = i;            }        }        int area = 0, root = A[0];        for(i = 0; i < maxInd; ++i){                if(root < A[i]) root = A[i];            else area += (root - A[i]);        }        for(i = n-1, root = A[n-1]; i > maxInd; --i){            if(root < A[i]) root = A[i];            else area += (root - A[i]);        }        return area;    }}
0 0
原创粉丝点击