zoukankan      html  css  js  c++  java
  • 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 is able to trap after raining.

    For example, 
    Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

    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!

    此题和之前的container with most water有些类似,most water里面求的是装最多的水,且里面没有bar,而这道题里面水在哪个bar已经告诉我们了,并且中间由很多的bar,也是用two pointer来做,判定条件也几乎一样,看左右两边哪个bar小哪个进行移动,这里面需要设定两个maxleft,maxright变量,分别表示指针走过的额区域里面bar最大的高度,如果指针所到之处没有max大,则max-pointer为该指针所处位置的水深,否则(大于等于)max为指针所处bar的高度,代码如下:

    public class Solution {

        public int trap(int[] height) {

            int left = 0;

            int right = height.length-1;

            int maxleft = 0;

            int maxright = 0;

            int sum = 0;

            while(left<right){

                if(height[left]<=height[right]){

                    if(height[left]>=maxleft){

                        maxleft = height[left];

                    }else{

                        sum+=maxleft-height[left];

                    }

                    left++;

                }else{

                    if(height[right]>=maxright){

                         maxright = height[right];

                    }else{

                        sum+=maxright-height[right];

                    }

                    right--;

                }

                

            }

            return sum;

        }

    }

  • 相关阅读:
    判断开始时间不能小于结束时间
    angular1.0使用echarts点刷新再次调用echarts方法
    解决angular4.0打包后不能再继续打包
    html拼接+layer按钮
    angular.js+echarts
    nginx配置
    NET_Framework_4.0installer.rar
    IIS6.0开启gzip压缩
    IIS的应用程序池优化方法
    远程桌面连接电脑后键盘失灵解决
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357303.html
Copyright © 2011-2022 走看看