zoukankan      html  css  js  c++  java
  • [Leetcode] 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], return6.

    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!

    题意:求所有能收集到的雨水

    思路:

    代码如下:

     1 class Solution {
     2 public:
     3     int trap(int A[], int n) 
     4     {
     5         int maxIdx=0;
     6         for(int i=0;i<n;++i)
     7         {
     8             if(A[i]>A[maxIdx])
     9                 maxIdx=i;
    10         }
    11 
    12         int left=0,right=0;
    13         int sum=0;
    14         for(int i=0;i<maxIdx;++i)   //计算左边容量
    15         {
    16             if(left>A[i])
    17                 sum+=left-A[i];
    18             else
    19                 left=A[i];
    20         }
    21         for(int i=n-1;i>maxIdx;i--)     //加上右边容量
    22         {
    23             if(right>A[i])
    24                 sum+=right-A[i];
    25             else
    26                 right=A[i];
    27         }
    28 
    29         return sum;    
    30     }
    31 };

    方法二:这题和最大水容器有点类似。定义两个指针,分别指向数组的两端,然后从两边向中间变历。具体思路:取两端中值较小(lower)的那段开始向中间遍历,若下一比lower小,则sum加上两者差值就行,left++,对应的值再和lower比较,若还是小于则继续加上差值,若不小于了,则将该值重新和right对应的值比较,重新确定lower值。重复上述过程。这里要注意的是:若连续是左端(右端)为较小值那端,Lower应该是固定的,直到条件不满足。代码如下:

     1 class Solution {
     2 public:
     3     int trap(int A[], int n) 
     4     {
     5         int left=0,right=n-1;
     6         int sum=0;
     7 
     8         while(left<right)
     9         {
    10             int lower=min(left,right);
    11             if(A[left]<A[right])
    12             {
    13                 left++;
    14                 while(left<right&&A[left]<lower)
    15                     sum+=A[lower]-A[left];
    16             }
    17             else
    18             {
    19                 right--;
    20                 while(left<right&&A[right]<lower)
    21                     sum+=A[lower]-A[right];
    22             }
    23         }
    24         return sum;
    25     }
    26 };
  • 相关阅读:
    8.1.1 播放合成声音
    CSS 用伪类 :after 选择器清除浮动
    javascript 拖拽
    javascript 回到顶端
    用 console.time()和 console.timeEnd() 测试你的 javascript 代码执行效率
    【风马一族_代码英语】代码英语之五
    【风马一族_代码英语】代码英语之四
    【风马一族_代码英语】代码英语之三
    【风马一族_Android】第4章Android常用基本控件
    【风马一族_日常灵感】在美国得到的人生感悟
  • 原文地址:https://www.cnblogs.com/love-yh/p/7191029.html
Copyright © 2011-2022 走看看