Trapping Rain Water

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

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

這裏寫圖片描述

Difficulty:Hard

TIME:20MIN

解法

記得之前做過一道題Container With Most Water,如果有那道題的經驗,那麼這道題也不難解決。

既然知道積累雨水是基於比較小的邊,那麼我們從比較小的邊開始遍歷,直到找到另一個長度大於等於它的邊,那麼就可以着手計算這個區域內的雨水了(其實採用累加計算,找到長度大於等於它的邊,就已經計算了好了這個區域內的雨水)

int trap(vector<int>& height) {
    if(height.size() < 3)
        return 0;
    int result = 0;
    int left = 0,right = height.size() - 1;
    int maxLeft = height[left], maxRight = height[right];
    while(left <= right) {
        if(maxLeft >= maxRight) { //從邊長比較小的邊開始遍歷(保證會遇到邊長比較大的邊)
            if(height[right] >= maxRight)
                maxRight = height[right]; //重置邊長
            else
                result += maxRight - height[right]; //累加雨水量
            right--;
        }
        else {
            if(height[left] >= maxLeft)
                maxLeft = height[left];
            else
                result += maxLeft - height[left];
            left++;
        }
    }
    return result;
}

代碼的時間複雜度爲O(n)

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