LeetCode 42 Trapping Rain Water 双指针+思维
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Solution
我们需要求出整个能蓄水多少。不妨考虑在位置 \(i\), 它能存储的水是多少。注意的一点是,当前位置的水量由左右侧最小值来决定。但一侧的高度我们需要维护最大值。
- 如果当前位置已经是某一侧的最大值了,此时显然存不了水
- 否则存储的容量则是: \(\min (lmax-rmax) -h\)
点击查看代码
class Solution {
private:
    int ans=0;
    int lmax[20003];
    int rmax[20003];
public:
    int trap(vector<int>& height) {
        int n = height.size();
        lmax[0] = height[0];
        rmax[n-1] = height[n-1];
        for(int i=1;i<n;i++){
            lmax[i] = max(lmax[i-1], height[i]);
        }
        for(int i=n-2;i>=0;i--){
            rmax[i] = max(rmax[i+1], height[i]);
        }
        for(int i=0;i<n;i++){
            ans+= min(lmax[i], rmax[i])-height[i];
        }
        return ans;
    }
};
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号