2.1.15 Trapping Rain Water

Link: https://oj.leetcode.com/problems/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.


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 Marcos for contributing this image!

我的思路:remember that 對每一個A[i], 它存儲的水量等於它的左右兩邊的最大值, max(left), max(right),取兩者的最小值,然後減去A[i].

min(max(left), max(right)) - A[i]

問題是max(left)可以通過從左向右循環得到,max(right)怎麼得到?

Approach I: 三次遍歷。1 從左往右,對每個柱子,找左邊最大值。2 從右往左,對每個柱子,找右邊最大值。3 求每個柱子上面的面積並累加。

我的代碼:一次過。可以不再做。

Time: O(n), Space: O(1)

public class Solution {
    public int trap(int[] A) {
        if(A.length <=2) return 0;
         //get max left
         int[] maxL = new int[A.length];
         maxL[0] = 0;
         for(int i = 1; i < A.length; i++){
             maxL[i] = Math.max(maxL[i-1], A[i-1]);
         }
         //get max right
         int[] maxR = new int[A.length];
         maxR[A.length-1] = 0;
         for(int i = A.length-2; i >=0; i--){
             maxR[i] = Math.max(maxR[i+1], A[i+1]);
         }
         //get water
         int sum = 0;
         for(int i = 0; i < A.length; i++){
             int diff = Math.min(maxL[i], maxR[i])-A[i];
             if(diff >0){
                sum += diff;
             }
         }
         return sum;
    }
}

Note: Don't forget this! Otherwise has Runtime Error. 

if(A.length <=2) return 0;

Approach II: 把第二,三次遍歷合起來。

public class Solution {
    public int trap(int[] A) {
        int n = A.length;
        if(n <=2) return 0;
        //get max left
        int[] maxL = new int[n];
        maxL[0] = 0;
        for(int i = 1; i < n; i++){
            maxL[i] = Math.max(maxL[i-1], A[i-1]);
        }
        //combine get max right and sum together
        int sum = 0;
        int maxR = A[n-1];
        for(int i = n-2; i >=0; i--){
            int diff = Math.min(maxL[i], maxR)-A[i];
            if(diff > 0){
                sum += diff;
            }
            if(A[i] > maxR){
                maxR = A[i];
            }
        }
        return sum;
    }
}



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