蓄水池

/**
 * 给定一个数组,求出该数组的蓄水数(10分)
比如数组是 [2,1,2],那么中间1这个位置就能蓄水1
比如数组是 [3,1,2,3] , 那么中间这个1,2这个位置分别蓄水2和1,所以总蓄水数是 3
现在给定数组:
[7,2,3,9,4,7,3,8] 
求出这个数组的蓄水数。
 * @ClassName Test7
 * @Description
 * @author rk
 */


public class Test7 {


    //最大值
    public static int max(int[] array){
        if(array.length == 0){
            return 0;
        }else{
            int max = array[0];
            for(int a : array){
                if(max < a){
                    max = a;
                }
            }
            return max;
        }
    }
    //最小值
    public static int min(int[] array){
        if(array.length == 0){
            return 0;
        }else{
            int min = array[0];
            for(int a : array){
                if(min > a){
                    min = a;
                }
            }
            return min;
        }
    }


    //蓄水量
    public static int total(int[] arr){
        int max = max(arr);
        int min = min(arr);
        int total = 0;
        int[] temp = new int[arr.length];
        for(int i = min; i < max; i++){
            for(int j = 0; j < arr.length; j++){
                if(arr[j] > i){
                    temp[j] = 1;
                }else{
                    temp[j] = 0;
                }
            }
             total += getWater(temp);
        }
        return total;
    }


    //获取临时数组中的和
    public static int getWater(int[] temp){
        int sum = 0;
        int i = 0;
        int j = temp.length -1;
            //左边第一个1
            while(i<j){
                if(temp[i] ==1){
                    break;
                }
                i++;
            }
            //右边第一个1
            while(j >= i){
                if(temp[j] ==1){
                    break;
                }
                j--;
            }
            for(int k = i+1;k<j;k++){
                if(temp[k] == 0) {
                    sum++;
                }
            }
            return sum;
    }


    public static void main(String[] args) {
//    int[] array = {2,1,2};
        int[] array = {7,2,3,9,4,7,3,8};  
        System.out.println(max(array));
        System.out.println(min(array));
        System.out.println(total(array));
    }










}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R_记忆犹新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值