Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
given[0,1,0,2,1,0,1,3,2,1,2,1], return6.
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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
https://oj.leetcode.com/problems/trapping-rain-water/
Idea 1: For a certain value a[i], the maximum amount of water that can be installed depends on the highest value before I leftmaxt[i] and the highest rightmax[i on the right of I], the volume of Water is min (left,right) –a[i]. : In order to calculate the height, the first pass computes the array leftmaxt from left to right, and the second time calculates the Rightmax from right to left. Space-time complexity is O (n).
Train of thought 2: The improvement idea 1, can use the constant space to fix. Specific ideas, first find the highest bar, and then the total on both sides of the calculation, Edge Computing edge update curheight.
For details, refer to this
Idea 1:
public class Solution {public int trap (int[] a) {if (a = = NULL | | A.length < 3) return 0;int n = a.length;int[] Leftmax = new int[n];int[] Rightmax = new Int[n];int i;int max = a[0];for (i = 1; i < n-1; i++) {Leftmax[i] = max;if (A[i] > max) max = a[i];} max = a[n-1];for (i = n-2; i > 0; i--) {Rightmax[i] = max;if (A[i] > max) max = a[i];} int count = 0;for (i = 1; i < n-1; i++) {int min = Leftmax[i] < Rightmax[i]? Leftmax[i]: rightmax[i];if (min ; A[i]) Count + = Min-a[i];} return count;} public static void Main (string[] args) {System.out.println (New solution (). Trap (new int[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));}}
Reference:
Http://fisherlei.blogspot.com/2013/01/leetcode-trapping-rain-water.html
Http://www.cnblogs.com/lichen782/p/Leetcode_Trapping_Rain_Water.html