【LeetCode】Trapping Rain Water

Trapping Rain Water 
Total Accepted: 8428 Total Submissions: 30087 My Submissions
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.

【LeetCode】Trapping Rain Water_第1张图片

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!
【解题思路】
求解装水最大量,其实就是求出数组中,所有的凹点,转化为两种思路。
1、从左到右求出每个点的左边最大高度,从右到左求出每个点右边的最大高度。
那么针对每个点,如果左右高度的最小值比该点高,就可以装水。

Java AC (380 ms)

public class Solution {
    public int trap(int[] A) {
		int len = A.length;
		int max = 0;
		int lArr[] = new int[len];
		for (int i = 0; i < len; i++) {
			lArr[i] = max;
			max = Math.max(max, A[i]);
		}
		max = 0;
		int rArr[] = new int[len];
		for (int i = len - 1; i >= 0; i--) {
			rArr[i] = max;
			max = Math.max(max, A[i]);
		}
		int mostWater = 0;
		for (int i = 0; i < len; i++) {
			int min = Math.min(lArr[i], rArr[i]);
			if (min > A[i]) {
				mostWater += min - A[i];
			}
		}
		return mostWater;
	}
}
2、求解出数组中的最大值,那么从左到最大值index扫描每个点,如果该点左侧最大值比当前点高,就可以装水。同理,从右到最大值index扫描,同样处理。最后累加就是最大值,其实就是1的思路变形。

Java AC (416 ms)

public class Solution {
    public int trap(int[] A) {
        if(A == null || A.length == 0){
            return 0;
        }
        int len = A.length;
        int maxValue = A[0];
        int maxIndex = 0;
        for(int i = 1; i < len; i++){
            if(A[i] > maxValue){
                maxValue = A[i];
                maxIndex = i;
            }
        }
        int mostWater = 0;
        int curNum = 0;
        for(int i = 0; i < maxIndex; i++){
            if(curNum > A[i]){
                mostWater += curNum - A[i];
            }else{
                curNum = A[i];
            }
        }
        curNum = 0;
        for(int i = len-1; i > maxIndex ; i--){
            if(curNum > A[i]){
                mostWater += curNum - A[i];
            }else{
                curNum = A[i];
            }
        }
        return mostWater;
    }
}


你可能感兴趣的:(【LeetCode】Trapping Rain Water)