LetCode 42. 接雨水

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
// O(mn)解法,超时
// class Solution {
// public:
//     int trap(vector<int>& height) {
//         int Max = 0;
//         int res = 0;
//         if (height.size() <= 0)
//             return 0;
//         int index = -1;
//         for (int i = 0; i < height.size(); i++)
//             Max = max(Max, height[i]);
//         for (int i = Max; i > 0; i--){
//             for (int j = 0; j < height.size(); j++){
//                 if (height[j] == Max){
//                     if (index != -1)
//                         res += (j - index - 1), index = j;
//                     else
//                         index = j;
//                     height[j]--;
//                 }
//             }
//             index = -1;
//             Max--;
//         }
//         return res;
//     }
// };

// O(n)解法, 双指针
// 木桶原理,盛的水取决于最短板,我们设置两个指针从左右两端开始向中间靠拢,我们根据短的那一端向高的那一端靠拢。
// 然后过程中更新左右最高的柱子,来求的中间的蓄水量。
class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        int l = 0, r = height.size() - 1;
        int lmax = 0, rmax = 0;
        while(l < r){
            lmax = max(lmax, height[l]);
            rmax = max(rmax, height[r]);
            if (lmax < rmax){
                res += lmax - height[l];
                l++;
            }else{
                res += rmax - height[r];
                r--;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值