leetcode Trapping Rain Water


Trapping Rain Water

Total Accepted:2335 Total Submissions:8464 My Submissions

Givennnon-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 Marcosfor contributing this image!

Discuss


Find the highest, then from the start to the highest, then the last to the highest..

class Solution {
 public:
  int trap(int A[], int n) {
    if (n <= 2)
      return 0;
    int i, maxElevation = A[0], maxIndex = 0, h = 0, res = 0;
    for (i = 1; i < n; ++i)
      if (A[i] > maxElevation) {
        maxElevation = A[i];
        maxIndex = i;
      }
    for (i = 0; i <= maxIndex - 1; ++i) 
      if (A[i] >= h)
        h = A[i];
      else
        res += (h - A[i]);
    
    h = 0;
    for (i = n - 1; i >= maxIndex + 1; --i) 
      if (A[i] >= h)
        h = A[i];
      else
        res += (h - A[i]);
    return res;
  }
};


优质内容筛选与推荐>>
1、js console.log 打印 对像 数组 详解
2、Android ADB命令
3、SQLSERVER 2005 BI的帮助文档说明:
4、Python小项目三:用curses实现2048 标签: 2048python实验楼游戏 2017-07-01 22:12 50人阅读 评
5、Session


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn