首页 > 移动平台 > 详细

LeetCode - Trapping Rain Water

时间:2014-02-10 12:27:51      阅读:458      评论:0      收藏:0      [点我收藏+]

Trapping Rain Water

2014.2.10 03:25

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.

bubuko.com,布布扣

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!

Solution:

  The first time I tried to solve this problem, I thought I was supposed to scan the array from left to right, and calculate the amount of water every "pond" can hold. Finding the boundary of every "pond" proved to be difficult, and the code proved to be wrong...(x_x)

  During the second attempt, I changed my way of thinking. Instead of caring about how much water is held in a pond, it would be easier to calculate how much water is held in one grid, it is min(max_height_left_of_here, max_height_right_of_here) - height_of_here.

  Why? Because it has to be high at both ends and low in the middle to hold any water, isn‘t it?

  If that calculation above yields a negative result, it‘s simply 0. Because here it is too high, the water flows down and cannot be held.

  In this manner, we just have to calculate how much water is held at every position h[i] and add them up.

  Two extra arrays are needed to record the maximum heights at both ends.

  Therefore, total time complexity is O(n). Space complexity is O(n) as well.

Accepted code:

bubuko.com,布布扣
 1 // 5CE, 2WA, 1AC, "const int &x", constant value has no reference.
 2 class Solution {
 3 public:
 4     int trap(int A[], int n) {
 5         if (A == nullptr || n < 3) {
 6             return 0;
 7         }
 8         
 9         vector<int> vl(n), vr(n);
10         int i;
11         int max_val;
12         int result;
13         
14         max_val = 0;
15         for (i = 0; i <= n - 1; ++i) {
16             vl[i] = max_val;
17             max_val = mymax(max_val, A[i]);
18         }
19         max_val = 0;
20         for (i = n - 1; i >= 0; --i) {
21             vr[i] = max_val;
22             max_val = mymax(max_val, A[i]);
23         }
24         
25         result = 0;
26         for (i = 0; i < n; ++i) {
27             max_val = mymax(0, mymin(vl[i], vr[i]) - A[i]);
28             result += max_val;
29         }
30         vl.clear();
31         vr.clear();
32         
33         return result;
34     }
35 private:
36     int mymin(const int x, const int y) {
37         return (x < y ? x : y);
38     }
39     
40     int mymax(const int x, const int y) {
41         return (x > y ? x : y);
42     }
43 };
bubuko.com,布布扣

LeetCode - Trapping Rain Water

原文:http://www.cnblogs.com/zhuli19901106/p/3542216.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!