Topic
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] , return 6 .
Resolution
Test instructions: An array of grooves can be filled with water volume.
Train of thought: From the two ends to the middle, to the end of the container can be the edge of the volume of water, and then all the values minus the short edge value, find new two sides, and continue to iterate until the middle.
public class Solution {public int trap (int[] A) { if (A.length < 3) return 0; int ans = 0; int L = 0, r = a.length-1; while (L < R) {//find ' left edge ' and ' right edge ' while (L < r && A[l] = = 0) l++; while (L < r && A[r] = = 0) r--; Get the shoter edge, which decides the volum int min = math.min (A[l], a[r]); Compute the Volum from a[l] to a[r] int tmp = 0; for (int i = l; I <= R; i++) { if (A[i] >= min) { a[i] = min; } else { tmp + = min-a[i]; A[i] = 0; } } Add to the result ans + = tmp; } return ans; }}
"Upgrade" "O (N)"
First find valid on both sides, such as [0, 1, 2, 3, 0, 3, 2, 1, 0], incrementing the left and descending to the right is not water.
Then select the shorter edge, and if it is left, start right until you find a higher edge than the left, update the left side, and if it is shorter on the right, move left until you find a higher edge and update to the right.
public class Solution {public int trap (int[] A) {if (A.length < 3) return 0; int ans = 0; int L = 0, r = a.length-1; Find the left and right edge which can hold water while (L < R && A[l] <= a[l + 1]) l++; while (L < R && A[r] <= a[r-1]) r--; while (L < r) {int left = A[l]; int right = A[r]; if (left <= right) {//Add volum until a edge larger than the left edge while (L < R && left >= A[++l]) {ans + = left-a[l]; }} else {//add volum until an edge larger than the right volum while (L < R && A[--r] <= right) {ans + = right-a[r]; }}} return ans; }}
"Leetcode" trapping Rain water problem solving report