C++算法:接雨水

leetcode相关C++算法解答: https://github.com/Nereus-Minos/C_plus_plus-leetcode

题目:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
C++算法:接雨水_第1张图片
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

实例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1] 输出: 6

思路一:

从头开始循环,每次找到<=height[i]的数(没找到,则使用次高点计算),去掉中间的高度,剩下的就是这块区域(i~next)的大小,然后i=next继续

思路二(和盛最多的水类似):

双指针法:因为积水总是受到叫低的一端影响,所以可以每次将较低的指针朝着较高的一方移动,会到更高的就停止,将较低的指针移动,每次统计当前块的积水量

代码:

#if 0
//思路一:从头开始循环,每次找到<=height[i]的数(没找到,则使用次高点计算),去掉中间的高度,剩下的就是这块区域(i~next)的大小,然后i=next继续
class Solution {
public:
    int trap(vector& height) {
        
        int i = 0, j = 0, second_h = 0;
        int next;
        int ret = 0;
        
        int len = height.size();  //不能直接用height.size()-2因为当长度为0时,这个值不为-2
        
        while(i < len-2)
        {
            if(height[i] == 0)
            {
                i++;
                continue;
            }
            
            second_h = i+1;
            //不能用函数lower_bound,因为无序
            next = my_next(height, i+1, height.size(), height[i], second_h);
            cout<& height, int begin, int end, int target, int& second_h){
        
        for(int i = begin; i < end; i++)
        {
            if(height[second_h] <= height[i])
                second_h = i;
            
            if(height[i] >= target)
                return i;
        }
        
        return end;  //表明未找到
    }
};
#endif

#if 1
//双指针法:因为积水总是受到叫低的一端影响,所以可以每次将较低的指针朝着较高的一方移动,会到更高的就停止,将较低的指针移动,每次统计当前块的积水量
class Solution {
public:
    int trap(vector& height) {
        
        if(height.size() < 3)
            return 0;
        
        int temp1 = 0, temp2 = 0, i=0, j = height.size()-1, count = 0;
        while(i < j)
        {
            if(height[i] < height[j])
            {
                if(temp1 < height[i])
                    temp1 = height[i];
                else
                    count += temp1 - height[i];
                i++;
            }
            else
            {
               if(temp2 < height[j])
                    temp2 = height[j];
                else
                    count += temp2 - height[j];
                j--;
            }
        }
        return count;
    }
};
#endif

你可能感兴趣的:(C++算法)