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;

        }

    }

  • 相关阅读:
    路径专题
    java.lang.IllegalArgumentException: Result Maps collection does not contain value for java.lang.Integer
    DER input, Integer tag error的异常处理
    myeclipse,eclipse控制台输出乱码问题
    大话设计模式之简单工厂模式
    Maven安装与配置
    IDEA: 遇到问题Error during artifact deployment. See server log for details.详解
    IntelliJ IDEA 中 右键新建时,选项没有Java class的解决方法和具体解释
    微信内置浏览器和小程序的 User Agent 区别及判断方法
    WAMP 403 Forbidden禁止访问
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357303.html
Copyright © 2011-2022 走看看