方法一:(动态规划)

思路展示

对于下标 i,下雨后水能到达的最大高度等于下标 i 两边的最大高度的最小值,下标 i 处能接的雨水量等于下标 i 处的水能到达的最大高度减去 height[i]。

示例代码

class Solution {
public:
    int trap(vector<int>& height) {
        int len = height.size();
        vector<int> leftMax(len+2);
        for (int i = 1; i <= len; ++i) {
            leftMax[i] = max(leftMax[i - 1], height[i-1]);
        }

        vector<int> rightMax(len+2);
        for (int i = len; i >= 1; --i) {
            rightMax[i] = max(rightMax[i + 1], height[i-1]);
        }

        int ans = 0;
        for (int i =1; i <= len; ++i) {
            ans += min(leftMax[i], rightMax[i]) - height[i-1];
        }
        return ans;
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

效果展示

LeetCode---42. 接雨水(动态规划or单调栈or双指针三种写法)(求左右两边最大值中的最小值)(栈内元素从低到顶依次减小)_示例代码

方法二:(单调栈)

示例代码

class Solution {
public:
    int trap(vector<int>& height) {
        int len=height.size();
        stack<int> stk;
        int res=0;
        for(int i=0;i<len;i++){
            while(!stk.empty()&&height[stk.top()]<height[i]){
                int topIndex=stk.top();
                stk.pop();
                //判断其左边还有没有元素
                if(stk.empty()){
                    break;
                }
                //在对 top 计算能接的雨水量之后,left 变成新的 top
                //所以其不用出栈
                int leftIndex=stk.top();
                res+=(min(height[leftIndex],height[i])-height[topIndex])*(i-leftIndex-1);
                
            }
            stk.push(i);
        }
        return res;
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

效果展示

LeetCode---42. 接雨水(动态规划or单调栈or双指针三种写法)(求左右两边最大值中的最小值)(栈内元素从低到顶依次减小)_示例代码_02

方法三:(双指针)

思路展示

下标 i 处能接的雨水量由 leftMax[i] 和 rightMax[i] 中的最小值决定。

LeetCode---42. 接雨水(动态规划or单调栈or双指针三种写法)(求左右两边最大值中的最小值)(栈内元素从低到顶依次减小)_示例代码_03

示例代码

class Solution {
public:
    int trap(vector<int>& height) {
        int res=0;
        int leftMax=0,rightMax=0;
        int left=0,right=height.size()-1;
        while(left<right){
            leftMax=max(leftMax,height[left]);
            rightMax=max(rightMax,height[right]);
            //判断左右两边哪个值比较小,然后再用其对应侧的最大值减去较小的一边的值,就可以得到当前位置存的雨水的高度
            if(height[left]<height[right]){
                res+=leftMax-height[left];
                left++;
            }else{
                res+=rightMax-height[right];
                right--;
            }

        }
        return res;

        


    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

效果展示

LeetCode---42. 接雨水(动态规划or单调栈or双指针三种写法)(求左右两边最大值中的最小值)(栈内元素从低到顶依次减小)_leetcode_04