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.

class Solution {
public:
    int trap(vector<int>& height) {
        if (height.empty()) return 0;
        int res;
        int sum = 0;
        int tot = 0;
        int max = 0, pos = 0;
        int i;
        int a = height[0], b = height[height.size() - 1];
        for (i = 0; i < height.size(); ++i) sum += height[i];
        for (i = 0; i < height.size(); ++i) {
            if (max < height[i]) {
                max  = height[i];
                pos = i;
            } 
        }
        for (i = 0; i < pos; ++i) {
            if (height[i] < a) height[i] = a;
            else a = height[i];
        }
        for (i = height.size() - 1; i > pos; --i) {
            if (height[i] < b) height[i] = b;
            else b = height[i];
        }
        for (i = 0; i < height.size(); ++i) tot += height[i];
        res = tot - sum;
        return res;
        
    }
};

First calculate the number of bars there are. Second calculate the total number of water and bars. The answer is what we got at the second step plus that at the first one.

Time: O(n).

posted @ 2018-05-03 16:03  通通的蓝图  阅读(103)  评论(0编辑  收藏  举报