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     }
  • 相关阅读:
    indy 發郵件的一些說明
    一此常用三方组件的地址(持续更新)
    oraSession直连
    获取关机信息及键盘或鼠标无响应的时长
    DBConnection释放说明
    发送邮件
    文件操作
    plsql中的一些知識
    TNativeXML用法(轉)
    redux中createStore, conbineReducers的简易封装
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3415266.html
Copyright © 2011-2022 走看看