Trapping Rain Water

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 {
    public int trap(int[] A) {
        if(A == null || A.length == 0) return 0;
        int maxIndex = -1;
        int maxValue = Integer.MIN_VALUE;
        for(int i = 0; i < A.length; i++)
        {
            if(maxValue < A[i])
            {
                maxIndex = i;
                maxValue = A[i];
            }
        }
        int maxRes = 0;
        int curMax = A[0];
        for(int i = 1; i <= maxIndex; i++)
        {
            if(A[i] < curMax)
            {
                maxRes += curMax - A[i];
            }
            else
            {
                curMax = A[i];
            }
        }
        
        curMax = A[A.length - 1];
        for(int i = A.length - 1; i >= maxIndex; i--)
        {
            if(A[i] < curMax)
            {
                maxRes += curMax - A[i];
            }
            else
            {
                curMax = A[i];
            }
        }
        return maxRes;
    }
}
View Code

学习之处:

  抓住数组最高点的特征

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。