簡體   English   中英

令人困惑的2D陣列

[英]Confusing 2D arrays

為什么我的解決方案不起作用?

這是練習2D數組的練習,顯然我未能理解它們。 輸入是創建一個方法,該方法在Array [] []中找到最大的沙漏形整數。 數組的大小將始終為6x6,因此對於循環來說,x <4和y <4,整數值也將從-9到9,這就是為什么我的結果變量以-256開頭的原因(如果我以0開頭,則數組已滿)負值將無法正常工作)

樣本輸入

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

那就是沙漏形的輸出

2 4 4
  2
1 2 4

樣本輸出

19

我的輸出錯誤

13

方法如下:

公共類解決方案{public static int maximumHourglass(int [] [] buffer){

        int result = -256; 
        int currentSize = 0;

        for (int x=0; x<4; x++){
            for (int y=0; y<4; y++){
                currentSize = (buffer[x][y+2] + buffer[x+1][y+2] + buffer[x+2][y+2]
                                        + buffer[x+1][y+1]
                         + buffer[x][y] + buffer[x+1][y] + buffer[x+2][y]);
                if (currentSize > result) { result = currentSize;}
            }
        }

        return result;
    }
}

然后在main中使用我的maximumHourglass()方法。

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int arr[][] = new int[6][6];
    for(int i=0; i < 6; i++){
        for(int j=0; j < 6; j++){
            arr[i][j] = in.nextInt();
        }
    }
    System.out.println(Solution.biggestHourglass(arr));
}
}

我的結果與預期不符,我也不知道自己做錯了什么。 請不要粗魯,我還在學習。 謝謝!

public class Solution {
    public static int biggestHourglass(int[][] buffer){

        int result = -256; 
        int currentSize = 0;

        for (int x=0; x<4; x++){
            for (int y=0; y<4; y++){
                currentSize = (buffer[x+2][y] + buffer[x+2][y+1] + buffer[x+2][y+2]
                                        + buffer[x+1][y+1]
                         + buffer[x][y] + buffer[x][y+1] + buffer[x][y+2]);
                if (currentSize > result) { result = currentSize;}
            }
        }

        return result;
    }
}

我還沒有檢查過,但看起來像是弄亂​​了x和y軸。

所以基本上你采取了:

[x][_][x]
[x][x][x]
[x][_][x]

形狀代替:

[x][x][x]
[_][x][_]
[x][x][x]
currentSize = (buffer[x][y] + buffer[x][y+1] + buffer[x][y+2]
                                    + buffer[x+1][y+1]
                     + buffer[x+2][y] + buffer[x+2][y+1] + buffer[x+2][y+2]);
            if (currentSize > result) { result = currentSize;}

*尺寸計算應與上述步驟相同

(0,0)+(0,1)+(0,2)

  + (1,1) +

(2,0)+(2,1)+(2,2)

在您的第一次迭代中,依此類推*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM