leetcode-42 Trapping Rain Water

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38340127/article/details/89710367

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

 暴力搜索:分别找出该位置 左右两边最大值 求出 两个最大之中的最小值,减去当前位置的高度 表示此位置的雨水容量,循环遍历和得出结果。 

    //题意就是获取出 可以包含 的所有的雨水面积 找出两个峰值之间的数据 
    public int trap(int[] height) {
        int res=0;
        
        for(int i=0;i<height.length;i++){
            int leftMax=height[i];
            int rightMax = height[i];
            for(int left=0;left<i;left++) {
                leftMax = Math.max(leftMax, height[left]);
            }
            
            for(int right=i+1;right<height.length;right++) {
                rightMax = Math.max(rightMax, height[right]);
            }
            
            
            res+= Math.min(leftMax, rightMax)-height[i];
        }
        
        
        return res;
    }

对此方法优化方法一:对每个位置的左右最大值用一个list进行存储 在进行循环

暴力搜索优化方法二:分别从头尾开始,在left中遇到right比其大的 则结果加上差值  并继续left++  否则 结果加上差值  并继续right--

猜你喜欢

转载自blog.csdn.net/qq_38340127/article/details/89710367