leetcode 42. 接雨水

接到雨水的面积 = 总面积 - 柱子的面积 - 左边没有水的面积 - 右边没有水的面积
在这里插入图片描述

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if(n == 0) return 0;
        int res = 0;
        int max_height = *max_element(height.begin(), height.end());
        //用来保存没有水的case, 两个栈包含的元素都是单调不增的
        stack<int> left, right;
        //保存左边没有水的面积
        for(int i = 0; i < n; i++) {
            if(height[i] == max_height) break;
            if(left.empty()) left.push(max_height - height[i]);
            else {
                left.push(min(left.top(), max_height - height[i]));
            }
        }
        //保存右边没有水的面积
        for(int i = n-1; i >= 0; i--) {
            if(height[i] == max_height) break;
            if(right.empty()) right.push(max_height - height[i]);
            else {
                right.push(min(right.top(), max_height - height[i]));
            }
        }
        //总面积
        int total = max_height * n;
        //柱子的面积
        int pillar = 0;
        for(auto i : height)
            pillar += i;
        //没有水的面积
        int left_no_water = 0, right_no_water = 0;
        while(!left.empty()) {
            left_no_water += left.top();
            left.pop();
        }
        while(!right.empty()) {
            right_no_water += right.top();
            right.pop();
        }
        res = total - pillar - left_no_water - right_no_water;
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值