• 【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;
        }
    };

  • 相关阅读:
    JAVA开发环境配置
    Java volatile关键字解惑
    Java实验案例(接口)
    Java 实验案例(多态)
    Eclipse 快捷键大全
    全球免费开放的电子图书馆
    Java 实验案例(类和对象篇)
    Java IO流(二)
    Linux zsh 实用配置
    Js远程调用封装
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4164763.html
Copyright © 2020-2023  润新知