LeetCode:Trapping Rain Water(装雨水问题)

来源:互联网 发布:picasa软件官方下载 编辑:程序博客网 时间:2024/06/11 22:35
        原题: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.首先可以想到用堆栈。如果当前高度比堆栈顶端的高度小,则当前下标进栈,且累加积水面积;如果当前高度比堆栈顶端的高度大,则出栈,且累加积水面积,如此循环。

        堆栈里始终维护的是高度依次递减的柱形。所以可以考虑下图的三种情况。

  

         (1)当前高度比堆栈内高度小,直接进栈,且累加黄色部分面积。

         (2)当前高度大于堆栈内高度,则首先累加黄色部分面积,退栈,计算绿色部分面积,进栈。这个过程需要保存已经处理过的黄色部分的高度lastHeight。

class Solution {public:    int trap(int A[], int n) {        if(A==NULL || n<=2)return 0;stack<int> s;s.push(0);int i=1,sum = 0;int lastHeight = 0;while(i<n){lastHeight = 0;while(A[i]>=A[s.top()]){sum += (i-s.top()-1)*(A[s.top()]-lastHeight);lastHeight = A[s.top()];s.pop();if(s.empty()){s.push(i++);lastHeight = 0;}}sum += (i-s.top()-1)*(A[i]-lastHeight);s.push(i++);}return sum;    }};
        2. 双指针方法。首尾各一个指针向中间移动,移动的过程中累加面积。
class Solution {public:    int trap(int A[], int n) {        if(A==NULL || n<=2)return 0;int sum = 0;int left = 0, right = n-1;int maxLeft = A[0], maxRight = A[n-1];while(left<right){if(A[left]<A[right]){if(maxLeft>A[left])sum += maxLeft-A[left++];elsemaxLeft = A[left++];}else{if(maxRight>A[right])sum += maxRight-A[right--];elsemaxRight = A[right--];}}return sum;    }};
        上述的maxLeft和maxRight可以只用一个值。

class Solution {public:    int trap(int A[], int n) {        if(A==NULL || n<=2)return 0;int sum = 0;int left = 0, right = n-1;int max = 0;while(left<right){if(A[left]<A[right]){if(max>A[left])sum += max-A[left++];elsemax = A[left++];}else{if(max>A[right])sum += max-A[right--];elsemax = A[right--];}}return sum;    }};


        两种方法的时间复杂度均为O(n),但方法1需要额外维护一个堆栈。

0 0
原创粉丝点击