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;

        }

    }

  • 相关阅读:
    OM Shipping 授权
    Account Summary 汇总模板
    OM Record is currently being worked on by another user, Please try to update it later.
    Initialization SQL Statement – Custom 配置错误,导致无法加载FORM
    ReOpen a Closed Inventory Accounting Period [ID 472631.1]
    IBM AIX User Lists
    Killing Oracle Sessions
    APPFND01016 (GL > Setup > Flexfields > Key > Rules)
    OM: release hold的时候,又遇到限制:You are not authorized to release this hold.
    SO History
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357303.html
Copyright © 2011-2022 走看看