接雨水-LintCode

给出 n 个非负整数,代表一张X轴上每个区域宽度为 1 的海拔图, 计算这个海拔图最多能接住多少(面积)雨水。
接雨水-LintCode_第1张图片
示例:
如上图所示,海拔分别为 [0,1,0,2,1,0,1,3,2,1,2,1], 返回 6。

挑战:
O(n) 时间, O(1) 空间
O(n) 时间, O(n) 空间也可以接受

O(n) 时间, O(n) 空间

#ifndef C363_H
#define C363_H
#include
#include
#include
using namespace std;
class Solution {
public:
    /*
    * @param heights: a list of integers
    * @return: a integer
    */
    int trapRainWater(vector<int> &heights) {
        // write your code here
        if (heights.empty())
            return 0;
        vector<int> lv;
        vector<int> rv;
        int lmax = 0;
        int rmax = 0;
        int len = heights.size();
        lv.push_back(0);
        for (int i = 1; i < len; ++i)
        {
            lmax = lmax>heights[i-1] ? lmax : heights[i-1];
            lv.push_back(lmax);
        }
        rv.push_back(0);
        for (int j = len - 1; j > 0; --j)
        {
            rmax = rmax > heights[j] ? rmax : heights[j];
            rv.push_back(rmax);
        }
        reverse(rv.begin(), rv.end());
        int num = 0;
        for (int k = 0; k < len; ++k)
        {
            if (heights[k] <= lv[k] && heights[k] <= rv[k])
            {
                num += ((lv[k] < rv[k] ? lv[k] : rv[k]) - heights[k]);
            }
        }
        return num;
    }
};
#endif

O(n) 时间, O(1) 空间

#ifndef C363_H
#define C363_H
#include
#include
#include
using namespace std;
class Solution {
public:
    /*
    * @param heights: a list of integers
    * @return: a integer
    */
    int trapRainWater(vector<int> &heights) {
        // write your code here
        if (heights.empty())
            return 0;
        int l = 0;
        int r = heights.size() - 1;
        int lmax = 0, rmax = 0;
        int num = 0;
        while (lif (lmaxelse
            {
                num += (rmax - heights[r]);
                --r;
            }
        }
        return num;
    }
    int maxVal(int a, int b)
    {
        return a > b ? a : b;
    }
};
#endif

你可能感兴趣的:(LintCode)