LeetCode Online Judge 题目C# 练习 - 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.

 1         public static int TrappingRainWater(int[] A)
 2         {
 3             if (A.Length <= 2)
 4                 return 0;
 5 
 6             int h = 0;
 7             // find the highest index
 8             for (int i = 0; i < A.Length; i++)
 9             {
10                 if (A[i] > A[h])
11                     h = i;
12             }
13 
14             int water = 0;
15             int p = 0;
16             // calculate from left to highest
17             for (int i = 1; i < h; i++)
18             {
19                 if (A[p] > A[i])
20                     water += A[p] - A[i];
21                 else
22                     p = i;
23             }
24 
25             p = A.Length - 1;
26             // calculate from right to highest
27             for (int i = A.Length - 2; i > h; i--)
28             {
29                 if (A[p] > A[i])
30                     water += A[p] - A[i];
31                 else
32                     p = i;
33             }
34 
35             return water;
36         }

代码分析:

  这是我一开始复习就在别人的面经上看到的题,数数手指也快2年了,唉。。。。什么时候才能给我OFFER啊??

  1. 找到最高的index

  2. 从左往右算water 的体积(面积)。p = 0, 如果A[i] < A[p],差值就可以承载水,如果A[i] >= A[p] ,p = i

  3. 从右往左在加一次water。 同理。

posted @ 2012-10-22 22:21  ETCOW  阅读(240)  评论(0编辑  收藏  举报