1. 程式人生 > 實用技巧 >接雨水-暴力演算法

接雨水-暴力演算法

演算法參考: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; }