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

    分析

    思路参考

    AC代码

    class Solution {
    public:
        int trap(vector<int>& height) {
            if (height.empty())
                return 0;
    
            int len = height.size();
    
            int lhs = 0, rhs = len - 1, secHeight = 0;
    
            int area = 0;
    
            //从两边向中间统计,分别统计每个竖立格子可以盛的水量
            while (lhs < rhs)
            {
                if (height[lhs] < height[rhs])
                {
                    secHeight = max(height[lhs], secHeight);
                    //加上lhs竖格的盛水量
                    area += secHeight - height[lhs];
                    //左侧右移一格
                    lhs++;
                }
                else{
                    secHeight = max(height[rhs], secHeight);
                    //加上rhs竖格的盛水量
                    area += secHeight - height[rhs];
                    //右侧左移一格
                    rhs--;
                }//fi
            }//while
    
            return area;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    封装/继承
    模板
    常用模块-re模块1
    包常用模块
    模块和软件开发的目录规范
    Hadoop 综合大作业
    hive基本操作与应用
    用mapreduce 处理气象数据集
    熟悉常用的HBase操作,编写MapReduce作业
    爬虫大作业
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214832.html
Copyright © 2011-2022 走看看