1, to today to complete 39 questions, but also need to continue to refuel. Let's analyze the problem of rainwater today.
Given n non-negative integers representing an elevation mapwhereThe width
of each bar is 1, compute how much water it isable to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1],return 6.
Thought: The area filled with water minus the area without water.
Rain = Water_sum-nowater_sum
Calculating water_sum effectively is the key to this problem.
2, a region can be water-bearing because of the formation of a large and small to large pits.
Define RIGHT_MAX[0--N-1], which holds the maximum value from right-to-left search. such as Right_max[i], indicating the column on the I, the highest column on the right is the value of right_max[i].
Similarly defined left_max[0--n-1]
The area of the column after irrigation is min (Left_max[i], right_max[i]) because of the short plate effect.
So to the 0 to n-1 and the Min (i), and then get the water_sum, the answer is easy to draw. The code is as follows.
The main idea is to turn the problem of rainwater into water-free and poor-seeking.
With the help of two matrix Left_max, Right_max saves the intermediate results, subtly reducing many computational amounts.
#include"stdafx.h"#include<iostream>using namespacestd;classSolution { Public: intTrapintA[],intn);};//Accepted, O (n)intSolution::trap (intA[],intN) {//take care of extreme situations! if(n = =0)return 0; int*right_max =New int[n]; intTmp_max = a[n-1]; Right_max[n-1] = a[n-1]; //the area when there is no water intNowater_sum = a[n-1]; for(inti = n2; I >=0; --i) {if(A[i] >Tmp_max) Tmp_max=A[i]; Right_max[i]=Tmp_max; Nowater_sum+=A[i]; } int*left_max =New int[n]; Tmp_max= a[0]; left_max[0] = a[0]; for(inti =1; I < n; ++i) {if(A[i] >Tmp_max) Tmp_max=A[i]; Left_max[i]=Tmp_max; } //calculate the area when water is available intWater_sum =0; for(inti =0; I < n; ++i) {water_sum+=min (left_max[i], right_max[i]); } Delete []right_max; delete []left_max; returnWater_sum-nowater_sum;}int_tmain (intARGC, _tchar*argv[]) { inta[ A] = {0,1,0,2,1,0,1,3,2,1,2,1}; Solution SLU; intresult = Slu.trap (A, A); return 0;}