leetcode-42. 接雨水-双指针-哪个指针小就移动哪个指针

一、题目

leetcode-42. 接雨水-双指针-哪个指针小就移动哪个指针_第1张图片

思路一

leetcode-42. 接雨水-双指针-哪个指针小就移动哪个指针_第2张图片

代码一:双指针

class Solution {
public:
    int trap(vector<int>& height) {
        int size=height.size();
        int left=0,right=size-1;
        //表示left_max左边最大值,right_max右边最大值
        int left_max=0,right_max=0;
        int Count=0;
        for(int i=0;i<size;++i){
            //left小于则left++
            if(height[left]<height[right]){
                //height[left]>left_max就更新left_max
                if(height[left]>left_max){
                    left_max=height[left];
                }
                //否则就加入进去
                else{
                    Count=Count+left_max-height[left];
                }
                left++;
            }
            else{
                if(height[right]>right_max){
                    right_max=height[right];
                }
                else{
                    Count=Count+right_max-height[right];
                }
                right--;
            }
        }
        return Count;
    }
};

二、思路二

采用动态规划:
1、求出每一个柱子可以接的水
2、这个柱子可以接的水为它左边和右边的最大值中的小的一个,然后再减去它当前的值
步骤:
1、新建两个数组,分别用来保存当前节点左边的最大值和当前节点右边的最大值
2、再遍历一遍原数组,从1到size-1,计算它左边的最大值和右边的最大值中的小的一个,然后再减去当前值

三、代码二

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.empty())
        {
            return 0;
        }
        int *dpl=new int[height.size()];
        int *dpr=new int[height.size()];

        int size=height.size();
        dpl[0]=height[0];
        dpr[size-1]=height[size-1];
        for(int i=1;i<size;++i)
        {
            dpl[i]=max(dpl[i-1],height[i]);
        }
        for(int i=size-2;i>=0;--i)
        {
            dpr[i]=max(dpr[i+1],height[i]);
        }
        int Count=0;
        for(int i=1;i<size-1;++i)
        {
            int temp=min(dpl[i-1],dpr[i+1])-height[i];
            if(temp>0)
            {
                Count+=temp;
            }
        }
        return Count;
    }
};

你可能感兴趣的:(LeetCode刷题,牛客网刷题,动态规划,leetcode)