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;
    }
};

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/80960228