leetcode Trapping Rain Water

原创 2013年12月02日 22:19:12

Trapping Rain Water

 Total Accepted: 2335 Total Submissions: 8464My Submissions

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!

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


LeetCode Trapping Rain Water等雨水的凹槽容量

最后黑体字的Thanks Marcos的意思是让我们放大我们的想象力,因为上图很容易误导我们的。如果只有上图的情况的话,我们可以很好用贪心法解决,但是,用贪心法是会出错的,因为如果我们计算当前最低点,...

leetcode || 42、 Trapping Rain Water

problem: Given n non-negative integers representing an elevation map where the width of each...

[leetcode]42. Trapping Rain Water(Java)

https://leetcode.com/problems/trapping-rain-water/#/description Given n non-negative inte...

Leetcode-42 Trapping in Rain Water

题目:             示例输入:                                                                              ...
  • qzq2514
  • qzq2514
  • 2017年03月18日 11:18
  • 247

leetcode学习笔记:Trapping Rain Water

Trapping Rain Water  Total Accepted: 8785 Total Submissions: 31229My Submissions Given n...

[Leetcode] Trapping Rain Water (Java)

Given n non-negative integers representing an elevation map where the width of each bar is 1, comput...

[Leetcode] 42. Trapping Rain Water 解题报告

题目: Given n non-negative integers representing an elevation map where the width of each bar is 1, ...

leetcode 42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, comput...

[Leetcode 42, Hard] Trapping Rain Water

[Leetcode 42, Hard] Trapping Rain Water

leetcode之路042 Trapping Rain Water

题目大意:给定n个非负的整数来代表高度图,每个条的宽度为1。计算下雨后它能装多少的水。 例:0,1,0,2,1,0,1,3,2,1,2,1], 返回 6 思路: 1、从左往右进行以下操作,先找到...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode Trapping Rain Water
举报原因:
原因补充:

(最多只允许输入30个字)