2017-04-18 85 views
0

我試圖解決這個問題就在這裏:https://leetcode.com/problems/trapping-rain-water/#/description掙扎調試Java解決方案,本文給出了算法

我的代碼提供了不正確的答案,但我不明白爲什麼。當我看着它,然後在頭腦中運行時,我無法弄清楚它有什麼問題。

這裏是我的解決方案: (請不要爲我提供了一個更加高效的方法的信息,如果可能的話,我想嘗試找出答案我自己)。

public class Solution { 
    public int trap(int[] height) { 
     int totalWaterTrapped = 0; 
     for (int i = 0; i < height.length; i++){ 
      if (i == 0){ 
       continue; 
      } else if (i == (height.length - 1)){ 
       continue; 
      } else { 
       int tallestLeftwardHeight = height[i]; 
       for (int x = i; x >= 0; x--){ 
        if (height[x] > tallestLeftwardHeight){ 
         tallestLeftwardHeight = x; 
        } 
       } 
       int tallestRightwardHeight = height[i]; 
       for (int y = i; y < height.length; y++){ 
        if (height[y] > tallestRightwardHeight){ 
         tallestRightwardHeight = y; 
        } 
       } 

       totalWaterTrapped += (Math.min(tallestLeftwardHeight, tallestRightwardHeight) - height[i]); 
      } 
     } 
     return totalWaterTrapped; 
    } 
} 

非常感謝您的幫助。

+1

添加問題在這裏的講話,而不是鏈接到它 –

回答

0
   if (height[x] > tallestLeftwardHeight){ 
        tallestLeftwardHeight = x; 
       } 

應該

   if (height[x] > tallestLeftwardHeight){ 
        tallestLeftwardHeight = height[x]; 
       } 

   if (height[y] > tallestRightwardHeight){ 
        tallestRightwardHeight = y; 
       } 

應該

   if (height[y] > tallestRightwardHeight){ 
        tallestRightwardHeight = height[y]; 
       } 
+0

哎,這樣一個愚蠢的錯誤!真的非常感謝你! –