[Leetcode] 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!

仔细想想感觉这道题应该是扫一遍就能得到结果的。。。对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i](均不包含自身)。如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight。时间复杂度是O(n)。

 1 class Solution {

 2 public:

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

 4         int maxHeight = 0;

 5         vector<int> leftMostHeight(n, 0);

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

 7             leftMostHeight[i] = maxHeight;

 8             maxHeight = (maxHeight > A[i]) ? maxHeight : A[i];

 9         }

10         maxHeight = 0;

11         vector<int> rightMostHeight(n, 0);

12         for (int i = n - 1; i >= 0; --i) {

13             rightMostHeight[i] = maxHeight;

14             maxHeight = (maxHeight > A[i]) ? maxHeight : A[i];

15         }

16         int water = 0, height;

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

18             height = min(leftMostHeight[i], rightMostHeight[i]) - A[i];

19             water += (height > 0) ? height: 0;

20         }

21         return water;

22     }

23 };

 下面是扫一遍的代码:

 1 class Solution {

 2 public:

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

 4         int left = 0, right = n - 1;

 5         int height = 0, res = 0;

 6         while (left < right) {

 7             if (A[left] < A[right]) {

 8                 height = max(height, A[left]);

 9                 res += height - A[left];

10                 ++left;

11             } else {

12                 height = max(height, A[right]);

13                 res += height - A[right];

14                 --right;

15             }

16         }

17         return res;

18     }

19 };

 

 

你可能感兴趣的:(LeetCode)