接雨水-暴力算法

算法参考:https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484482&idx=1&sn=9503dae2ec50bc8aa2ba96af11ea3311&source=41#wechat_redirect

    public static int q() {
        int sumWater = 0;
        int[] a = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        for (int i = 1; i < a.length - 1; i++) {
            //左侧最大值
            int highLeftMax = 0;
            //右侧最大值
            int highRightMax = 0;
            int left = i - 1;
            int right = i + 1;
            //获得左侧最大值
            while (left >= 0) {
                highLeftMax = Math.max(highLeftMax, a[left]);
                left--;
            }
            //获取右侧最大值
            while (right < a.length) {
                highRightMax = Math.max(highRightMax, a[right]);
                right++;
            }
            //同时满足左侧最大值大于当前值,并且右侧最大值大于当前值,才可以接雨水
            if (highLeftMax > a[i] && highRightMax > a[i]) {
                int temp = Math.min(highLeftMax, highRightMax) - a[i];
                sumWater += temp;
                System.out.println("i=" + i + ";值=" + a[i] + ";highLeftMax=" + highLeftMax + ";highRightMax=" + highRightMax + ";sumWater=" + temp);
            }
        }
        System.out.println(sumWater);
        return sumWater;
    }

 

posted @ 2020-07-15 14:34  使用D  阅读(224)  评论(0编辑  收藏  举报