首页 > 移动平台 > 详细

Trapping Rain Water

时间:2014-04-20 07:26:32      阅读:524      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
    int trap(int A[], int n) {
        int result = 0;
        int l = 0,r = n-1;
        while(A[l]==0)l++;
        while(A[r]==0)r--;
        int h = 0;
        h = min(A[l],A[r]);
        while(l < r)
        {
            if(A[l] <= h)
            {
                result += h - A[l];
                l++;
            }
            else if(A[r] < h)
            {
                result += h - A[r];
                r--;
            }
            else if(A[l] > h && A[r] == h)
            {
                r--;
            }
            else if(A[r] > h && A[l] == h)
            {
                l++;
            }
            else if(A[l]>h &&A[r]>h)
            {
                h = min(A[l],A[r]);
            }
        }
        return result;
    }
};

  

Trapping Rain Water,布布扣,bubuko.com

Trapping Rain Water

原文:http://www.cnblogs.com/pengyu2003/p/3675706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!