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         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int left = -1;
 5         int right = -1;
 6         int sum = 0;
 7         int i = 0;
 8         for(; i < A.length; i ++){
 9             if(left == -1 && A[i] != 0){
10                 left = i;
11                 break;
12             }
13         }
14         for(i = A.length - 1; i >= 0; i --){
15             if(right == -1 && A[i] != 0){
16                 right = i;
17                 break;
18             }
19         }
20         
21         if(left != -1){
22             i = left + 1;
23             while(i < A.length){
24                 if(A[left] <= A[i]){
25                     for(int j = left; j < i; j ++){
26                         sum += A[left] - A[j];
27                     }
28                     left = i;
29                 }
30                 i ++;
31             }
32         }
33         
34         
35         if(right != -1){
36             i = right - 1;
37             while(i > -1){
38                 if(A[right] < A[i]){
39                     for(int j = right; j > i; j --){
40                         sum += A[right] - A[j];
41                     }
42                     right = i;
43                 }
44                 i --;
45             }
46         }
47         return sum;
48     }
49 }

 第二遍:

 1 public class Solution {
 2     public int trap(int[] A) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int n = A.length;
 5         int[] b = new int[n];
 6         int M=-10000;
 7         for (int i=0; i<n; i++){
 8             b[i] = M;
 9             M = Math.max( M, A[i] );
10         }
11         M=-10000;
12         int ret=0;
13         for (int i=n-1; i>=0; i--){
14             if ( i!=n-1 && i!=0 ){
15                 if ( A[i] < Math.min( M, b[i] ) )
16                     ret += Math.min( M, b[i] )-A[i];
17             }
18             M = Math.max( M, A[i] );
19         }
20         return ret;
21     }
22 }

 

posted on 2013-10-11 11:58  Step-BY-Step  阅读(152)  评论(0编辑  收藏  举报

导航