1

与えられた三角数は次のとおりです。

4
5  3
9  2  21
1  46 12  8
.... upto n rows.

各行から最大の数値を取得して合計する必要があります。

n行すべて(2D配列など)をどこにどのように配置するか、およびそこから各行を選択する方法を理解できません。

4

3 に答える 3

1
public static void main(String[] args) {

    int[][] matrix = { { 4 }, { 5, 3 }, { 9, 2, 21 }, { 1, 46, 12, 8 } };
    int sum = 0;
    for (int i = 0; i < matrix.length; i++) {
        int maxInRow = matrix[i][0];
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.println(matrix[i][j]);

            if (maxInRow < matrix[i][j]) {
                maxInRow = matrix[i][j];
            }
        }
        sum = sum + maxInRow;

    }
    System.out.println(sum);

}

これを試して:

于 2013-02-11T10:31:25.583 に答える
1

List<List<Integer>>の代わりにを使用できる場合は、次の方法を使用するarrayと、作業が非常に簡単になりますCollections.max

// The below syntax is called `double braces initialization`.
List<List<Integer>> triangularNumber = new ArrayList<List<Integer>>() {
    {
        // Add inner lists to the outer list.
        add(Arrays.asList(4)); 
        add(Arrays.asList(5, 3));
        add(Arrays.asList(9, 2, 21));
        add(Arrays.asList(1, 46, 12, 8));
    }
};

int sum = 0;
for (List<Integer> innerList: triangularNumber) {
    sum += Collections.max(innerList);
}

System.out.println(sum);
于 2013-02-11T10:44:57.067 に答える
0

地図を使ってみませんか?各行のインデックスを知る必要がある場合は、次のように行うことができます。

Map<Integer, List<Integer>> numbers = new HashMap<Integer, List<Integer>();

使用できる最大のものを見つけることに関して:

Collections.max(...)

JDKドキュメント

これでうまくいくはずです。

于 2013-02-11T12:42:32.307 に答える