所以我正在努力将这个逻辑从2D应用程序转换为在一维数组中运行。对我来说最让人困惑的是数组以及它们的循环将如何运作。任何输入将不胜感激!
LcgRandom rand = new LcgRandom();
int[][] triangle = new int[ROWS][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
//System.out.println(triangle[i]);
for (int j = 0; j <= i; j++)
triangle[i][j] = rand.next();
//System.out.println(triangle[i]);
}
//Calculate row sums
int[][] rowSums = new int[triangle.length][];
for (int i = 0; i < rowSums.length; i++) {
rowSums[i] = new int[triangle[i].length + 1];
rowSums[i][0] = 0;
for (int j = 0; j <= i; j++)
rowSums[i][j + 1] = rowSums[i][j] + triangle[i][j];
}
//find the smallest triangle
long minSum = 0;
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
long curSum = 0;
for (int k = i; k < triangle.length; k++) {
curSum += rowSums[k][k - i + 1 + j] - rowSums[k][j];
if (minSum>curSum)
minSum=curSum;
System.out.println(minSum);
}
}
}
return Long.toString(minSum);
}
答案 0 :(得分:0)
如果您打算以行主格式存储2D数组,即首先存储所有row1元素,然后线性存储row2元素,则需要调整索引计算。
假设您的2D数组有R行和C列,则每行都有C个元素。因此,您的索引计算如下:
array_1d[j + i*C] == array_2d[i][j] // This is true.
因此,您的1D数组中将包含R * C
个元素。