[Leetcode] Trapping Rain Water

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:

通过扫描两边数组,找到该列的左边,右边最大的值。

 1 public class Solution {
 2     public int trap(int[] A) {
 3         int N = A.length;
 4         if (N < 3)
 5             return 0;
 6         int[] l2r = new int[N];
 7         int[] r2l = new int[N];
 8         int left = 0;
 9         int right = 0;
10         for (int i = 0; i < N; ++i) {
11             l2r[i] = left;
12             left = Math.max(left, A[i]);
13         }
14         for (int i = N - 1; i >= 0; --i) {
15             r2l[i] = right;
16             right = Math.max(right, A[i]);
17         }
18         int sum=0;
19         for(int i=0;i<N;++i){
20             int temp=Math.min(l2r[i], r2l[i])-A[i];
21             if(temp>0)
22                 sum+=temp;                
23         }
24         return sum;
25     }
26 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4049640.html