面试题 17.21. 直方图的水量

给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的直方图,在这种情况下,可以接 6 个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

class Solution {
public:
    int trap(vector<int>& height) {
        int n=height.size();    
        int ans=0;
        for(int i=1;i<n-1;i++){
            int l=0,r=0;
            // Find the tallest bar on the right
            for(int j=i;j<n;j++)r=max(r,height[j]);
            // Find the tallest bar on the left
            for(int j=i;j>=0;j--)l=max(l,height[j]);
            //add the minimum of l_max and r_max and subtract the height of the current bar
            ans+=min(l,r)-height[i];
        }
        return ans;
    }
};

同样的思路,预处理left[]和right[],优化掉内部循环

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if(n<=2)return 0;
        vector<int> left(n), right(n);
        left[0] = height[0];
        for (int i = 1; i < n; i++)
            left[i] = max(left[i-1], height[i]);
        right[n-1] = height[n-1];
        for (int i = n-2; i >= 0; i--)
            right[i] = max(right[i+1], height[i]);

        int ans = 0;
        for (int i = 1; i < n-1; i++) {
            ans += max(0, min(left[i-1], right[i+1]) - height[i]);
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/xxxsans/p/14609180.html