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!

    思路:

    找到最高的一个板子,然后从两边往中间靠近,如果高度小于当前的最大高度,结果加上当前最大高度-板子高度,否则不存水,只更新最大高度即可。

    代码:

     1     int trap(int A[], int n) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int i;
     5         int curmax, max = INT_MIN, maxIndex, result = 0;
     6         if(n == 0)
     7             return 0;
     8         for(i = 0; i < n; i++){
     9             if(A[i] > max){
    10                 max = A[i];
    11                 maxIndex = i;
    12             }
    13         }
    14         curmax = A[0];
    15         for(i = 1; i < maxIndex; i++){
    16             if(A[i] < curmax){
    17                 result += (curmax-A[i]);
    18             }
    19             else{
    20                 curmax = A[i];
    21             }
    22         }
    23         curmax = A[n-1];
    24         for(i = n-2; i > maxIndex; i--){
    25             if(A[i] < curmax){
    26                 result += (curmax-A[i]);
    27             }
    28             else{
    29                 curmax = A[i];
    30             }
    31         }
    32         return result;
    33     }
  • 相关阅读:
    Step by Step To Create a K8S Cluster
    Linux简单操作指令
    安装redis 最新版 redis-6.2.6
    GCC升级到11.2.0
    SQL开窗函数
    SQL 树形结构递归查询
    一文详解python的类方法,普通方法和静态方法
    _new_()与_init_()的区别
    关于Python的import机制原理
    【原创】android内存管理-hprof文件
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3415266.html
Copyright © 2011-2022 走看看