首页 > 其他 > 详细

leetcode(42)接雨水

时间:2019-07-11 20:41:04      阅读:99      评论:0      收藏:0      [点我收藏+]

接雨水

解题思路:分冶法+递归

class Solution {
    public int trap(int[] height) {
        int len = height.length;
        if(len<=2){
            return 0;
        }
        return trap(height,0,len);
    }
    public int trap(int[] height,int start,int end){
        if(end-start<=2){
            return 0;
        }
        int max = maxv(height,start,end);
        int max2 = maxv(height,start,max);
        int max3 = maxv(height,max+1,end);
        int trap2 = trap(height,start,max2+1);
        int trap3 = trap(height,max3,end);
        int temp = 0;
        int sum = 0;
        for(int i=max2+1;i<max;i++){
            temp = height[max2];
            sum += height[i]<temp?(temp-height[i]):0;
        }
        for(int i=max+1;i<max3;i++){
            temp = height[max3];
            sum += height[i]<temp?(temp-height[i]):0;
        }
        return sum + trap2+trap3;
    }
    public int maxv(int[] height,int start,int end){
        int max = start;
        for(int i=start+1;i<end;i++){
            if(height[i]>height[max]){
                max = i;
            }
        }
        return max;
    } 
}

 

leetcode(42)接雨水

原文:https://www.cnblogs.com/erdanyang/p/11172518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!