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
.
Solution 1:
public class Solution { /** * The algorithm in this solution is smart and the running time is O(n). We introduce * a stack to save the indices which correspond a sequence of decreasing elements of A. * @param A -int array. * @return int -total capacity * @author Averill Zheng * @version 2014-06-22 * @since JDK 1.7 */ public int trap(int[] A) { int capacity = 0, length = A.length; if(length > 0){ int max = A[0]; Stack<Integer> maxIndex = new Stack<Integer>(); maxIndex.push(0); for(int i = 1; i < length; ++i) { if(A[maxIndex.peek()] <= A[i]){ if(max <= A[maxIndex.peek()]){ //case 1, max = A[i]; maxIndex.pop(); maxIndex.push(i); } else{//case 2 while(!maxIndex.empty() && A[maxIndex.peek()] <= A[i]){ int temp = A[maxIndex.pop()]; if(!maxIndex.empty()) capacity += (Math.min(A[maxIndex.peek()], A[i]) - temp) * (i - maxIndex.peek() - 1); } maxIndex.push(i); max = Math.max(max, A[i]); } } else //case 3 maxIndex.push(i); } } return capacity; } }
solution2:
1 public class Solution { 2 public int trap(int[] A) { 3 int max = 0; 4 if(A.length > 1){ 5 int[] result = new int[A.length]; 6 result[0] = 0; 7 result[1] = 0; 8 int largest = (A[0] <= A[1])? A[1]: A[0]; 9 int largestIndex = (A[0]<= A[1])? 1 : 0; 10 for(int i = 2; i < A.length; ++i){ 11 int length = 0; 12 int sum = 0; 13 for(int j = i - 1; j > largestIndex; --j){ 14 if(A[j] < A[i]){ 15 ++length; 16 sum += A[j]; 17 } 18 else 19 break; 20 } 21 if(length == 0) 22 result[i] = result[i - 1]; 23 else 24 result[i] = Math.min(A[i], A[i - length - 1]) * length - sum + result[i - length - 1] ; 25 largest = (A[i] <= largest)? largest: A[i]; 26 if(largest == A[i]) 27 largestIndex = i; 28 } 29 max = result[A.length - 1]; 30 } 31 return max; 32 } 33 }