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 .
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!
Test instructions
Given an array, each index bit in the array represents a bar, and the value of the corresponding index bit represents the bar's height, bar width is 1. Calculate how much water this bar group can hold.
Ideas
, the sub-high and the highest can form the water area. So our aim is to find all the grooves in this area;
With A[0] as the left edge of the groove, we need to scan backward to find the first bar not less than a[0], assuming that is a[k], then a[0] and a[k] between the formation of a groove;
Then take A[k] as the left edge of the new groove, scan backward to find the first bar not less than a[k], assuming that is a[m], then a[k] and a[m] between the formation of a groove;
Backwards and forwards in turn.
Code
Class Solution {Public:int trap (int a[], int n) {if (n<3) return 0; int result=0; int left=0; int right=0; int maxheight=0; The maximum height of the left border to hold int maxindex=-1; The index position that is used to hold the maximum height of the left border to the left while (left<n-1) {right=left+1; maxheight=0; while (Right<n && A[right]<a[left]) {if (a[right]>=maxheight) {m Axheight=a[right]; Maxindex=right; } right++; if (right>=n) {///If no right boundary is found not below the left edge, the right=maxindex is calculated by taking the second high bar; }//Calculate the water storage of the current Groove int height=min (A[left], a[right]); Get water storage height for (int i=left+1; i<right; i++) {result+=height-a[i]; } left=right; } return result; }};