Leetcode題解42-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.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcosfor contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6


思路:雙指針從左右遍歷,維護當前位置所對應的左側最高值和右側最高值,這兩者中的最小值與當前位置的差值即爲可儲水量


代碼

class Solution {
public:
    int trap(vector<int>& height) {
        int Len = height.size();
        if(Len <= 2) return 0;   //需要三個以上才能儲水
        vector<int> leftArr(Len,0), rightArr(Len,0);   // 維護兩側最高值的數組
        int maxLeft=0, maxRight=0, sumWater = 0;
        for(int i = 0; i <height.size(); i++){
            leftArr[i] = max(height[i],maxLeft);     
            maxLeft = max(height[i],maxLeft);   //更新MaxLeft
        }
        for(int i = Len-1; i >=0; i--){
            rightArr[i] = max(height[i], maxRight);
            maxRight = max(height[i], maxRight);
        }     
        for(int i = 0;  i < Len; i++){
            sumWater += min(leftArr[i], rightArr[i]) - height[i];
        }
        return sumWater;        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章