LeetCode 42 接雨水 动态规划+空间优化

参考题解:

https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/

https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/327718

(我觉得你讲双指针那里完全没讲清楚,官方题解下的这个评论倒是讲得很好。)

 

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

left和right都不是从最边缘开始取的,因为边缘两个柱子接不到雨水,然后遍历所有剩下的柱子,判断能接多少水,加到最终的结果里。

class Solution {
public:
    int trap(vector& height) {
        int num = height.size();
        int left = 1;
        int right = num-2;
        int max_left = 0;
        int max_right = 0;
        int minn;
        int sum = 0;
        for(int i = 1; i < num - 1; ++i){
            if(height[left-1] < height[right+1]){
                max_left = max(height[left-1],max_left);
                minn = max_left;
                if(minn > height[left]){
                    sum += (minn-height[left]);
                }
                ++left;
            }
            else{
                max_right = max(height[right+1],max_right);
                minn = max_right;
                if(minn > height[right]){
                    sum += (minn-height[right]);
                }
                --right;
            }
        }
        return sum;
    }
};
class Solution:
    def trap(self, height: List[int]) -> int:
        left=0
        right=len(height)-1
        left_max=right_max=0
        ans=0
        while left<=right:
            if left_max

 

你可能感兴趣的:(动态规划,leetcode,算法,动态规划,c++,python)