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!

这道题做的比较艰辛,一开始自己想的是一个用stack的解法,感觉过于繁琐(出栈,入栈,计算容积),但未尝不是一个好的尝试,这个方法还是有点小问题,过后会好好想清楚。看了网上提示完成了最终的方法,这个方法两次遍历数组,第一次遍历找每个元素右边最大的元素,第二次遍历寻找每个元素左边最大的元素,同时计算该index可以存放的水容积: min{lefthighest, righthighest}-A[i]

用两个array

 1 public class Solution {
 2     public int trap(int[] A) {
 3         int[] left = new int[A.length];
 4         int[] right = new int[A.length];
 5         int sum = 0;
 6         for (int i=0; i<A.length; i++) {
 7             if (i == 0) left[i] = 0;
 8             else {
 9                 left[i] = Math.max(left[i-1], A[i-1]);
10             }
11         }
12         for (int i=A.length-1; i>=0; i--) {
13             if (i == A.length - 1) right[i] = 0;
14             else {
15                 right[i] = Math.max(right[i+1], A[i+1]);
16             }
17             if (Math.min(left[i], right[i]) > A[i]) {
18                 sum += Math.min(left[i], right[i]) - A[i];
19             }
20         }
21         return sum;
22     }
23 }

用一个array和一个变量

 1 public class Solution {
 2     public int trap(int[] A) {
 3         int[] left = new int[A.length];
 4         int right = 0;
 5         int sum = 0;
 6         for (int i=0; i<A.length; i++) {
 7             if (i == 0) left[i] = 0;
 8             else {
 9                 left[i] = Math.max(left[i-1], A[i-1]);
10             }
11         }
12         for (int i=A.length-1; i>=0; i--) {
13             if (i == A.length - 1) right = 0;
14             else {
15                 right = Math.max(right, A[i+1]);
16             }
17             if (Math.min(left[i], right) > A[i]) {
18                 sum += Math.min(left[i], right) - A[i];
19             }
20         }
21         return sum;
22     }
23 }

 

相关文章: