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!

 

 第一遍:
 1 public class Solution {

 2     public int trap(int[] A) {

 3         if(A == null || A.length < 3) return 0;

 4         int start = 0, end = A.length - 1;

 5         while(A[start] == 0){

 6             start ++;

 7         }

 8         while(A[end] == 0){

 9             end --;

10         }

11         int left = start;

12         int sum = 0;

13         for(int i = start + 1; i <= end; i ++){

14             if(A[i] >= A[left]){

15                 for(int j = left + 1; j < i; j ++){

16                     sum += A[left] - A[j];

17                 }

18                 left = i;

19             }

20         }

21         int right = end;

22         for(int i = end - 1; i >= start; i --){

23             if(A[i] > A[right]){

24                 for(int j = i + 1; j < right; j ++){

25                     sum += A[right] - A[j];

26                 }

27                 right = i;

28             }

29         }

30         return sum;

31     }

32 }

 

第三遍:

 1 public class Solution {

 2     public int trap(int[] A) {

 3         if(A == null || A.length < 3) return 0;

 4         int sum = 0;

 5         int start = 0, end = A.length - 1;

 6         while(start < A.length && A[start] == 0) start ++;

 7         while(end > -1 && A[end] == 0) end --;

 8         int per = start, cur = start + 1;

 9         for(; cur <= end; cur ++){

10             if(A[cur] >= A[per]){

11                 for(int i = per + 1; i < cur; i ++)

12                     sum += A[per] - A[i];

13                 per = cur;

14             }

15         }

16         per = end; cur = end - 1;

17         for(; cur >= start; cur --){

18             if(A[cur] > A[per]){

19                 for(int i = cur + 1; i < per; i ++)

20                     sum += A[per] - A[i];

21                 per = cur;

22             }

23         }

24         return sum;

25     }

26 }

 

你可能感兴趣的:(water)