Monday, July 21, 2014

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.

左右两个指针往中间遍历,记录对应左右两边的最大值更新,移动最大值小的那一边,这样可以只遍历数组一遍。
public class Solution {
    //Time: O(n)
    public int trap(int[] A) {
        if (A == null || A.length <= 1) {
            return 0;
        }
        
        int left = 0;
        int leftmax = A[left];
        int right = A.length - 1;
        int rightmax = A[right];
        int sum = 0;
        while (left < right) {
            if (rightmax > leftmax) {
                left++;
                sum += leftmax - A[left] > 0 ? leftmax - A[left] : 0;
                leftmax = Math.max(leftmax, A[left]);
            } else {
                right--;
                sum += rightmax - A[right] > 0 ? rightmax - A[right] : 0;
                rightmax = Math.max(rightmax, A[right]);
            }
        }
        return sum;
    }
}

No comments:

Post a Comment