1. 程式人生 > >LintCode 363: Trapping Rain Water (蓄水池經典題!!!)

LintCode 363: Trapping Rain Water (蓄水池經典題!!!)

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

Trapping Rain Water

Example
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Challenge
O(n) time and O(1) memory

O(n) time and O(n) memory is also acceptable.

注意這道題不要跟直方
圖求最大矩形混淆。那道題可以用單調棧實現。

注意某個矩形塊上方的水就是該矩形塊左右側最高的矩形塊的高度的較低值與其本身高度的差

解法1:
先求出最高的矩形長度maxHeight和maxIndex,然後從左右兩邊分頭算。算出最高高度後,maxIndex左邊的矩形塊的右側最高長度就是maxHeight, 只需要找出其左側最高長度即可。
maxIndex右邊的矩形塊的左側最高長度就是maxHeight,只需要找出其右側最高長度即可。
程式碼如下:

class Solution {
public:
    /**
     * @param heights: a list of integers
     * @return: a integer
     */
    int trapRainWater(vector<int> &heights) {
        int len = heights.size();
        if (len == 0) return 0;
        
        int maxHeight = 0;
        int maxIndex = 0;
        
        for (int i = 0; i < len; ++i) {
            if (maxHeight < heights[i]) {
                maxHeight = heights[i];
                maxIndex = i;
            }
        }
        
        int sum = 0;
        maxHeight = 0;
        for (int i = 0; i < maxIndex; ++i) {
            if (maxHeight > heights[i]) {
                sum += maxHeight - heights[i];
            } else {
                maxHeight = heights[i];
            }
        }
        
        maxHeight = 0;
        for (int i = len - 1; i > maxIndex; --i) {
            if (maxHeight > heights[i]) {
                sum += maxHeight - heights[i];
            } else {
                maxHeight = heights[i];
            }
        }
        
        return sum;
    }
};

解法2:單調棧。
感覺這題也能用單調(遞減?)棧來做。先求出最高的矩形,然後兩邊分別用單調棧?
TBD.

解法3:雙指標。類似解法1。
注意某個矩形塊上方的水就是該矩形塊左右側最高的矩形塊的高度的較低值與其本身高度的差。所以用雙指標,一左一右夾逼,每次更新lMax和rMax,而heights[i]上方的水就是lMax和rMax的最小值與heights[p1]或heights[p2]的差。
程式碼如下:

class Solution {
public:
    /**
     * @param heights: a vector of integers
     * @return: a integer
     */
    int trapRainWater(vector<int> &heights) {
        int len = heights.size();
        if (len == 0) return 0;
        
        int lMax = 0, rMax = 0;
        int p1 = 0, p2 = len - 1;
        int sum = 0;
        
        while(p1 < p2) {
            if (lMax < heights[p1]) {
                lMax = heights[p1];
            }
            if (rMax < heights[p2]) {
                rMax = heights[p2];
            }
            
            if (lMax  < rMax) {
                sum += lMax - heights[p1];
                p1++;
            } else {
                sum += rMax - heights[p2];
                p2--;
            }
        }
        return sum;
        
    }
};