程序员面试金典 面试题 17.21. 直方图的水量

题目链接

面试题 17.21. 直方图的水量

思路分析

通过从左向右遍历,从右向左遍历求得相对位置的最大值,然后从左向右遍历用他俩的最小值减去高度累加即可。

class Solution {
public:
    int trap(vector<int>& height) {
        std::ios::sync_with_stdio(false);
        if(height.empty()) return 0;
        int n = height.size();
        vector<int> left(n), right(n);
        left[0] = height[0], right[n - 1] = height[n - 1];
        for(int i = 1; i < n; i++)
            left[i] = max(left[i - 1], height[i]);
        for(int i = n - 2; i >= 0; i--)
            right[i] = max(right[i + 1], height[i]);
        int res = 0;
        for(int i = 0; i < n; i++)
            res += min(left[i], right[i]) - height[i];
        return res;
    }
};
posted @ 2021-04-02 23:04  蒟蒻颖  阅读(31)  评论(0编辑  收藏  举报