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!
Analyse:the water can trapped equals to the min (Left[i], right[i])-height[i], whereas Left[i] and Right[i] is the LA Rgest number of the left and right part of the number.
Runtime:8ms.
1 classSolution {2 Public:3 intTrap (vector<int>&height) {4 intn =height.size ();5 if(N <=1)return 0;6 7 int*left =New int[n];8 intmax = height[0];9 for(inti =1; I < n-1; i++) {//Find the largest of the left of a elementTenLeft[i] =Max; One if(Height[i] >max) AMax =Height[i]; - } -max = Height[n-1]; the intresult =0; - for(intj = N-2; J >=0; j--){ - intdiff = min (max, left[j])-height[j];//The water trapped at index i - if(diff >0) +Result + =diff; - if(Height[j] >max) +Max =Height[j]; A } at returnresult; - } -};
Trapping Rain Water