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代码:

  1. public int trap(int[] A) {
  2. int size = A.length;
  3. int[] lheight = new int[size];
  4. int[] rheight = new int[size];
  5. int max=0;
  6. for(int i=0;i<size;i++) {
  7. //if(i==0) height[i]=A[i];
  8. lheight[i]=max;
  9. if(A[i]>max) {
  10. max=A[i];
  11. lheight[i]=max;
  12. }
  13. }
  14. max=0;
  15. for(int i=size-1;i>=0;i--) {
  16. rheight[i]=max;
  17. if(A[i]>max) {
  18. max=A[i];
  19. rheight[i]=max;
  20. }
  21. }
  22. int sum=0;
  23. for(int i=1;i<size-1;i++) {
  24. int minmax = Math.min(lheight[i-1],rheight[i+1]);
  25. if(minmax>A[i]) sum+=(minmax-A[i]);
  26. }
  27. return sum;
  28. }

C++代码:

  1. int trap(int A[], int n) {
  2. if(n==0) return 0;
  3. int water=0;
  4. int curHeight=0;
  5. int i=0;
  6. int mid=0;
  7. for(i=0;i<n;i++) {
  8. if(A[i]>A[mid]) {
  9. mid=i;
  10. }
  11. }
  12. for(i=0;i<mid;i++) {
  13. if(A[i]<curHeight) {
  14. water+=(curHeight-A[i]);
  15. } else curHeight=A[i];
  16. }
  17. curHeight=0;
  18. for(i=n-1;i>mid;i--) {
  19. if(A[i]<curHeight) water+=(curHeight-A[i]);
  20. else curHeight=A[i];
  21. }
  22. return water;
  23. }
posted @ 2014-08-10 15:09  purejade  阅读(85)  评论(0)    收藏  举报