zoukankan      html  css  js  c++  java
  • 【LeetCode】42. 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!

    双指针left,right分别从首尾开始扫,记当前left指针遇到的最大值为leftWall,right指针遇到的最大值为rightWall

    (1)leftWall <= rightWall

    left前进一个位置。

    对于left指针指向的位置,若存在被trap,则被trap的值为(leftWall-A[left])。

    解释如下:

    a.如果left与right之间不存在比leftWall大的值,那么i位置trap的值就取决与leftWall与rightWall的较小值,也就是leftWall

    b.如果left与right之间存在比leftWall大的值,其中离leftWall最近的记为newLeftWall,那么i位置trap的值就取决与leftWall与newLeftWall的较小值,也就是leftWall

    (2)leftWall > rightWall

    right后退一个位置。

    对于right指针指向的位置,被trap的值为(rightWall-A[right])。

    解释同上。

    class Solution {
    public:
        int trap(int A[], int n) {
            int ret = 0;
            int left = 0;
            int right = n-1;
            int leftWall = A[left];
            int rightWall = A[right];
            while(left < right)
            {
                if(leftWall <= rightWall)
                {
                    left ++;
                    if(A[left] <= leftWall)
                        ret += (leftWall - A[left]);
                    else
                        leftWall = A[left];
                }
                else
                {
                    right --;
                    if(A[right] <= rightWall)
                        ret += (rightWall - A[right]);
                    else
                        rightWall = A[right];
                }
            }
            return ret;
        }
    };

  • 相关阅读:
    CSS优先级及继承
    group by 与 order by
    软件开发升级指南(转)
    安装DELL服务器,安装Windows 2003 sp2 问题
    SQL SERVER 2005数据库总结
    C#操作INI文件(调用WindowsAPI函数:WritePrivateProfileString,GetPrivateProfileString)
    对RBS理解与使用
    WSS和MOSS的区别
    关于.net winform ComboBox数据绑定显示问题
    OpenNETCF.Desktop.Communication.DLL程序集的使用
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4164763.html
Copyright © 2011-2022 走看看