码迷,mamicode.com
首页 > 移动开发 > 详细

Trapping Rain Water

时间:2015-03-12 09:45:06      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

学习之处:

  抓住数组最高点的特征

Trapping Rain Water

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4331487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!