leetcode-42 Trapping Rain Water

问题描述:

Given n non-negative integers representing anelevation map where the width of each bar is 1, compute how much water it isable to trap after raining.

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

leetcode-42 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!

 

问题分析:

同样也是双指针法解决问题,类似的问题有:《leetcode-11 Container With Most Water》

找到左右边界,然后逐步向里逼近;时间复杂度O(n)

 

代码:

public class Solution {
   public int trap(int[] A) {
        // 双指针法,记录左右指针位置
        int left = 0, right = A.length - 1;
        int result = 0;
        // 记录左右边界的最高高度
        int maxLeft = 0, maxRight = 0;
       
        while (left <= right) {
            // 由于水桶效应,故与left,right较小值相关
            if (maxLeft <= maxRight) {
                if (A[left] > maxLeft)
                    maxLeft = A[left];
                else
                    result += (maxLeft -A[left]);
                left++;
            } else {
                if (A[right] > maxRight)
                    maxRight = A[right];
                else
                    result += (maxRight -A[right]);
                right--;
            }
        }
        return result;
   }
}


你可能感兴趣的:(leetcode-42 Trapping Rain Water)