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!

    双指针,需要把情况考虑全。

    class Solution {
    public:
        int trap(int A[], int n) {
            int result = 0;
            int l = 0,r = n-1;
            while(A[l]==0)l++;
            while(A[r]==0)r--;
            int h = 0;
            h = min(A[l],A[r]);
            while(l < r)
            {
                if(A[l] <= h)
                {
                    result += h - A[l];
                    l++;
                }
                else if(A[r] < h)
                {
                    result += h - A[r];
                    r--;
                }
                else if(A[l] > h && A[r] == h)
                {
                    r--;
                }
                else if(A[r] > h && A[l] == h)
                {
                    l++;
                }
                else if(A[l]>h &&A[r]>h)
                {
                    h = min(A[l],A[r]);
                }
            }
            return result;
        }
    };
    

      

  • 相关阅读:
    visual sudio开发工具使用小技巧
    JS去除右边的逗号
    下拉标题
    sp_addextendedproperty
    触发器的使用
    缺失一个正数
    组合总和 去重
    拖动 Drag
    n皇后问题
    括号生成
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3675706.html
Copyright © 2011-2022 走看看