码迷,mamicode.com
首页 > 移动开发 > 详细

42. Trapping Rain Water

时间:2017-07-04 13:21:11      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ons   blog   app   最大值   []   each   sea   trap   higher   

https://leetcode.com/problems/trapping-rain-water/#/solutions

Here is my idea: instead of calculating area by height*width, we can think it in a cumulative way. In other words, sum water amount of each bin(width=1).
Search from left to right and maintain a max height of left and right separately, which is like a one-side wall of partial container. Fix the higher one and flow water from the lower part. For example, if current height of left is lower, we fill water in the left bin. Until left meets right, we filled the whole container.

 左右指针、最大值维护、正序、逆序

class Solution {
public:
    int trap(int A[], int n) {
        int left=0; int right=n-1;
        int res=0;
        int maxleft=0, maxright=0;
        while(left<=right){
            if(A[left]<=A[right]){
                if(A[left]>=maxleft) maxleft=A[left];
                else res+=maxleft-A[left];
                left++;
            }
            else{
                if(A[right]>=maxright) maxright= A[right];
                else res+=maxright-A[right];
                right--;
            }
        }
        return res;
    }
};

  

42. Trapping Rain Water

标签:ons   blog   app   最大值   []   each   sea   trap   higher   

原文地址:http://www.cnblogs.com/apanda009/p/7115984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!