LeetCode: Trapping Rain Water

继续不争气看网上答案。。

 1 class Solution {

 2 public:

 3     int trap(int A[], int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         if (n < 2) return 0;

 7         vector<int> left(n, A[0]);

 8         vector<int> right(n, A[n-1]);

 9         int ret = 0;

10         for (int i = 1; i < n; i++) left[i] = max(left[i-1], A[i]);

11         for (int i = n-2; i >= 0; i--) right[i] = max(right[i+1], A[i]);

12         for (int i = 1; i < n-1; i++) {

13             int tmp = min(left[i], right[i]) - A[i];

14             ret += tmp > 0? tmp : 0;

15         }

16         return ret;

17     }

18 };

 C#

 1 public class Solution {

 2     public int Trap(int[] height) {

 3         int n = height.Length;

 4         if (n < 2) return 0;

 5         int[] left = new int[n];

 6         int[] right = new int[n];

 7         for (int i = 0; i < n; i++) {

 8             left[i] = height[0];

 9             right[i] = height[n-1];

10         }

11         int ans = 0;

12         for (int i = 1; i < n; i++) left[i] = Math.Max(left[i-1], height[i]);

13         for (int i = n-2; i >= 0; i--) right[i] = Math.Max(right[i+1], height[i]);

14         for (int i = 1; i < n-1; i++) {

15             int tmp = Math.Min(left[i], right[i]) - height[i];

16             ans += tmp > 0? tmp : 0;

17         }

18         return ans;

19     }

20 }
View Code

 

你可能感兴趣的:(LeetCode)