Describe
Given n non-negative integers representing an elevation map where the width of each bar is 1, computehow much wat Er it is able-trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Analysis:
For each pillar, find the tallest pillar on the left and right side, the area that the pillar can hold is min (max_left,max_right)-height. So
1. Scan from left to right, and for each pillar, the left maximum value is obtained;
2. Scan from right to left, for each column, the maximum right value;
3. Scan again and add up the area of each pillar.
Code
/*Trapping Train Water v2*/ intTrap (vector<int> &height) { intresult=0; intn =height.size (); int*left_flag =New int[n]; int*right_flag =New int[n]; memset (Left_flag, Int_max, n*sizeof(int)); memset (Right_flag, Int_max, n*sizeof(int)); left_flag[0] =0; Right_flag[n-1] =0; //Scan left for(inti =1; I < n; i++) { if(Height[i-1]>left_flag[i-1]) {Left_flag[i]= Height[i-1]; } Else{Left_flag[i]= Left_flag[i-1]; } } //Scan Right for(inti = n-2; I >=0; i--) { if(Height[i +1] > Right_flag[i +1]) Right_flag[i]= Height[i +1]; ElseRight_flag[i]= Right_flag[i +1]; } for(size_t i =0; I < n; i++) { intCompare = Min (Left_flag[i], right_flag[i])-Height[i]; Result+ = (compare>0? Compare:0); } Delete[] left_flag; Delete[] right_flag; returnresult; }
Related topics: (M) Container with the most water
Product of Array Except self
[Leetcode]trapping Rain Water