zoukankan      html  css  js  c++  java
  • Trapping Rain Water

    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!

    算法很简单,核心思想是:对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i]。(均不包含自身)。如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。

    有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight,在第二遍的同时就可以计算出i位置的结果了,而且并不需要开空间来存放rightMostHeight数组。

    时间复杂度是O(n),只扫了两遍。

    public class Solution {
        public int trap(int[] A) {
            
            int n = A.length;
            //no way to contain any water
            if(n <= 2) return 0;
            
            //1. first run to calculate the heiest bar on the left of each bar
            int[] lmh =new int[n]; //for the most height on the left
            lmh[0] = 0;
            int maxh =A[0]; // max height
            for(int i =1; i<n; i++){
                lmh[i] = maxh;
                if(A[i] > maxh) maxh = A[i];
            }
            
            int trapped = 0;
            
            
            //2. second run from right to left, 
            // caculate the highest bar on the right of each bar
            // and calculate the trapped water simutaniously
            maxh = A[n-1];
            for(int i = n-2; i>0; i--){
                int left = lmh[i];
                int right = maxh;
                //计算lmh 和 rmh 的最小值
                int container = Math.min(left, right);
                //如果当前值比 container 小,则能容水
                if(container > A[i]){
                    trapped += container - A[i];
                }
                
                if(maxh < A[i]) maxh = A[i];
            }
            
            return trapped;
        }
    }
  • 相关阅读:
    [Go] golang http下返回json数据
    [Go] Golang练习项目-邮箱imap网页版客户端工具
    [Go] 提供http服务出现两次请求以及处理favicon.ico
    [Go] 转换编码处理网页显示乱码
    [Go] go转换gbk为utf8
    [Go] golang x.(type) 用法
    [GO] go语言中结构体的三种初始化方式
    [PHP] create_function() 代码注入问题已经被弃用
    [Git] 彻底删除github上的某个文件以及他的提交历史
    [javascript] vuejs的elementui实现父子iframe通信
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3533064.html
Copyright © 2011-2022 走看看