【leetCode】42_接雨水

传统stack。还有更快的办法是:扫描出各个点左右的最高墙,从而得到该点的水柱高度。加总。

class Solution {
public:
    int trap(vector& height) {
        typedef int Height, IndX;
        typedef pair Wall;
        stack> s;
        int capacity = 0;
        int floor = 0x3f3f3f3f;
        if (height.empty())
            return 0;
        s.push(Wall(height[0], 0));
        for (int i = 1;i < height.size(); i ++){
            if (height[i] < s.top().first){
                if (floor > height[i])
                    floor = height[i];
                s.push(Wall(height[i], i));
            }
            else{
                while (!s.empty() && height[i] >= s.top().first){
                    capacity += (s.top().first - floor) * (i - s.top().second - 1);
                    floor = s.top().first;
                    s.pop();
                }
                if (!s.empty())
                    capacity += (height[i] - floor) * (i - s.top().second - 1);
                floor = height[i];
                s.push(Wall(height[i], i));
            }
        }
        return capacity;
    }
};

 

你可能感兴趣的:(leetCode)