LeetCode[One hard A Day] - Trapping Rain Water

Trapping Rain Water

算法一:对于array里的每一个位置来说,它的积水量等于(左边最高的墙和右边最高的墙中最小的一道墙)减去自己位置的高度。

            我们可以运用DP,第一次run存入左侧最高的数,第二次run计算右边最高的数,并与之前的比较得到最小值,最后与自己位数上的数比较,如果大于0累计到最终答案上。

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.empty()) return 0;
        vector<int> dp(height.size(), 0);
        int mx = 0; //test
        int res =0;
        for(int i=0; i<dp.size();i++){
            dp[i] = mx;
            mx = max(mx, height[i]);         
        }
        mx = 0;
        for(int i=dp.size()-1; i>=0; i--){
            dp[i] = min(mx, dp[i]);
            mx = max(mx, height[i]);
            if(dp[i]-height[i]>0) res += dp[i]-height[i];
        }
        return res;
    }
};


算法二: 想象一下水坑的形成就是两边较高中间低,然后以较低的一侧基准形成水坑。如果水坑中有比任何一侧墙高的,高的那个墙将代替两侧中的一面墙。

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.empty()) return 0;
        int l = 0;
        int r = height.size()-1;
        int res = 0;
        while(l<r){
            int mn = min(height[l], height[r]);
            if(mn==height[l]){
                l++;
                while(l<r && height[l]<mn) res += mn-height[l++];
            }
            else{
                r--;
                while(l<r && height[r]<mn) res += mn-height[r--];
            }

        }
        return res;
    }
};

还有一种code更简洁,但个人觉得更加难理解,见reference


算法三:用stack

reference:http://www.cnblogs.com/grandyang/p/4402392.html


猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/79797564
今日推荐