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
思路:
对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i](均不包含自身)。
如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。
有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight。 时间复杂度是O(n)。
public class Solution { public int trap(int[] A) { if(A == null || A.length < 1) return 0; int maxheight = 0; int[] leftMostHeight = new int[A.length]; for(int i =0; i < A.length; i++) { leftMostHeight[i] = maxheight; maxheight = maxheight > A[i] ? maxheight : A[i]; } maxheight = 0; int[] rightMostHeight = new int[A.length]; for(int i =A.length - 1; i>=0; i--) { rightMostHeight[i] = maxheight; maxheight = maxheight > A[i] ? maxheight : A[i]; } int water = 0; for(int i =0; i < A.length; i++) { int high = Math.min(leftMostHeight[i], rightMostHeight[i]) - A[i]; if(high>0) water += high; } return water;
}
}
解法二:
是两边往中间遍历, 记录当前第二高点secHight, 然后利用这个第二高点减去当前历经的柱子, 剩下就装水容量了; 两边比较时,最高的点不用动,只移动第二高点 public class Solution { public int trap(int[] A) {
int secHight = 0; int left = 0; int right =A.length; int area = 0; while (left < right){ if (A[left] < A[right]){ secHight = Math.max(A[left], secHight); area += secHight-A[left];//计算当前格的能装雨水的容量 left++; } else { secHight = Math.max(A[right], secHight); area += secHight-A[right]; right--; } } return area;
}
}
