给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水

 

/*给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。*/
    public static void main(String[] args) {
        int[] aa = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        //  int[] aa = {4,2,0,3,2,5};
        int c = 0;
        int i = test6(c, aa);
        System.out.println(i);
    }

    public static int test6(int c, int[] aa) {
        boolean type = true;
        boolean type2 = true;
        /*起点*/
        int st = 0;
        /*终点*/
        int ed = 0;
        for (int i = 0; i < aa.length; i++) {
            /*找出大于0的起点*/
            if (type && aa[i] > 0) {
                st = i;
                type = false;
            }
            /*找出大于0的终点*/
            if (type2 && aa[aa.length - i - 1] > 0) {
                ed = aa.length - i - 1;
                type2 = false;
            }
        }
        /*查找每一层能够接多少水*/
        for (int i = st; i <= ed; i++) {
            int b = aa[i] - 1;
            if (b < 0) {
                c = c + 1;
            } else {
                aa[i] = b;
            }
        }
        System.out.println(Arrays.toString(aa));
        //判断是否已经到顶层
        if (ed > 0 && st != ed) {
            return test6(c, aa);
        } else {
            return c;
        }

    }

 

posted @ 2026-01-08 15:02  黄橙  阅读(8)  评论(0)    收藏  举报