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

      

  • 相关阅读:
    关于vue的npm run dev和npm run build
    移动端meta行大全
    浅谈前端三大框架Angular、react、vue
    Web Workers
    Meta(其他信息)
    页面
    页面
    日期和时间
    ECharts教程(未完)
    页面
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3675706.html
Copyright © 2011-2022 走看看