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).

猜你喜欢

转载自www.cnblogs.com/ustcrliu/p/8985856.html
今日推荐