trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is 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 rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
思想:积水高度右左右最小高度以及自己高度决定,可以得到如下结论 sum +=- min(lheight[i],rheight[i]) - A[i] > 0
java代码:
- public int trap(int[] A) {
- int size = A.length;
- int[] lheight = new int[size];
- int[] rheight = new int[size];
- int max=0;
- for(int i=0;i<size;i++) {
- //if(i==0) height[i]=A[i];
- lheight[i]=max;
- if(A[i]>max) {
- max=A[i];
- lheight[i]=max;
- }
- }
- max=0;
- for(int i=size-1;i>=0;i--) {
- rheight[i]=max;
- if(A[i]>max) {
- max=A[i];
- rheight[i]=max;
- }
- }
- int sum=0;
- for(int i=1;i<size-1;i++) {
- int minmax = Math.min(lheight[i-1],rheight[i+1]);
- if(minmax>A[i]) sum+=(minmax-A[i]);
- }
- return sum;
- }
C++代码:
- int trap(int A[], int n) {
- if(n==0) return 0;
- int water=0;
- int curHeight=0;
- int i=0;
- int mid=0;
- for(i=0;i<n;i++) {
- if(A[i]>A[mid]) {
- mid=i;
- }
- }
- for(i=0;i<mid;i++) {
- if(A[i]<curHeight) {
- water+=(curHeight-A[i]);
- } else curHeight=A[i];
- }
- curHeight=0;
- for(i=n-1;i>mid;i--) {
- if(A[i]<curHeight) water+=(curHeight-A[i]);
- else curHeight=A[i];
- }
- return water;
- }

浙公网安备 33010602011771号