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.
对于每一个点来说,蓄水量 = min(左边的最高点,右边的最高点)-本身高度,于是两次遍历,一次用来找每个点的左边的最高点,一次用来找每个点的右边的最高点。
public class Solution { public int trap(int[] A) { int result = 0; if(A.length<3){ return 0; } int []temp = new int[A.length]; int left = A[0]; for(int i=1;i<A.length-1;i++){ if(A[i]<left){ temp[i] = left; }else if(A[i]>left){ left = A[i]; } } int right = A[A.length-1]; for(int i=A.length-2;i>0;i--){ if(A[i]<right){ if(temp[i]>0){ result += (min(temp[i],right)-A[i]); } }else if(A[i]>right){ right = A[i]; } } return result; } public int min(int a,int b){ return a>b?b:a; } }