【问题标题】:using 2-dimensional arrays is faster than two of 1-dimensional arrays? [duplicate]使用二维数组比两个一维数组快吗? [复制]
【发布时间】:2021-05-31 03:30:23
【问题描述】:
static int ud[] = new int[] { 0, 0, 1 };

static int lr[] = new int[] { -1, 1, 0 };

static int dirs[][] = { { 0, 1 }, { 1, 0 }, { 0, -1 } };

public static int solve(int r, int c, int dir) {
    if (r == n - 1 && c == m - 1)
        return v[r][c];

    if (dp[r][c][dir] != -INF)
        return dp[r][c][dir];

    visited[r][c] = true;
    int ans = -200000;

    for (int i = 0; i < 3; i++) {
        int nr = r + dirs[i][0]; # no time out
        int nc = c + dirs[i][1]; # no time out

        // int nr = r + ud[i]; # time out 
        // int nc = c + lr[i]; #  time out 
        if (nr < 0 || nc < 0 || nr >= n || nc >= m)
            continue;

        if (visited[nr][nc])
            continue;

        ans = Math.max(ans, solve(nr, nc, i) + v[r][c]);

    }
    visited[r][c] = false; 
    return dp[r][c][dir] = ans;
}

我想在二维数组中将 row,col 向上、向左、向右移动 所以我像往常一样声明了两个一维数组并提交了我的代码,但答案是失败 我声明了二维数组而不是一维数组中的两个,我提交了我的代码 答案通过了,不知道为什么 二维数组比两个一维数组快吗?

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    这取决于您如何使用一维数组。

    二维数组元素因此存储在内存中,而两个一维数组可能从不同的内存地址开始。

    如果你多次访问二维数组,它会更快,因为它的大部分值已经在缓存中。 这称为“空间局部性”。 另一方面,如果你一个一个地访问两个一维数组,它会迫使你的计算机将数据从内存加载到缓存中,这会很慢。

    无论如何,如果您发布两个版本的代码会更好。

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2012-11-13
    • 1970-01-01
    • 2017-07-17
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多