zoukankan      html  css  js  c++  java
  • 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!

    思路:这道题先找出中间最高的柱子,记下位置maxIndex。然后分别从两边开始向中间循环遍历。先从左边开始记下前一个的柱子高度sum1,然后与后一个的柱子高度相比较,如果比后面的高,则他们两的差额累加到water,反之,更新sum1。再者,从右边开始,相同思路。这样就可以计算出最后储水量。

    class Solution {
    public:
        int trap(int A[], int n) {
            if(n<2)
                return 0;
            int max=A[0];
            int maxIndex=0;
            for(int i=1;i<n;i++)
            {
                if(A[i]>max)
                {
                    max=A[i];
                    maxIndex=i;
                }
            }
            int water=0;
            int sum1=0;
            for(int i=0;i<maxIndex;i++)
            {
                if(sum1>A[i])
                {
                    water+=sum1-A[i];
                }
                else
                    sum1=A[i];
            }
            int sum2=0;
            for(int i=n-1;i>maxIndex;i--)
            {
                if(sum2>A[i])
                {
                    water+=sum2-A[i];
                }
                else
                    sum2=A[i];
            }
            return water;
        }
    };
  • 相关阅读:
    封装和参数调用(格式修改)
    今天休息
    2018.1.9内部类
    2018.1.8转型
    环境变量
    环境变量
    计算机的高级语言
    常用的设计模式
    常用的设计模式
    【python3】中 elif 的使用
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3652022.html
Copyright © 2011-2022 走看看