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;
    }
}



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