如果你想节省内存,你的解决方案看起来很棒 - 它被称为packed storage matrix。逐列,自上而下,您的数组将如下所示:1 2 6 3 7 8 4 1 9 5
我建议根据总和公式(n² + n) / 2(行和列为零)建议更简单的指数计算。
list_index = (column^2 + column) / 2 + row;
实现可能如下所示:
public class TriangularMatrix {
private final int[] list;
public TriangularMatrix(int size) {
list = new int[sumFormula(size)];
}
public int set(int row, int column, int value) {
validateArguments(row, column);
int listIndex = getListIndex(row, column);
int oldValue = list[listIndex];
list[listIndex] = value;
return oldValue;
}
public int get(int row, int column) {
validateArguments(row, column);
return list[getListIndex(row, column)];
}
private void validateArguments(int row, int column) {
if (row > column) {
throw new IllegalArgumentException("Row (" + row + " given) has to be smaller or equal than column (" + column + " given)!");
}
}
private int getListIndex(int row, int column) {
return sumFormula(column) + row;
}
private int sumFormula(int i) {
return (i*i + i) / 2;
}
}
有another question on SO讨论(负面)性能影响,尽管它与Fortran有关。