leetcode 1260. Shift 2D Grid(2D矩阵平移)

这篇博客探讨了如何高效地将二维矩阵平移k步,其中每个元素向右平移一位,边界元素按规则处理。作者提供了两种方法,第一种是通过计算平移后的坐标再倒推出原始坐标,第二种是一维下标检索法,这种方法更快,只需2ms。博客内容涉及矩阵操作、算法优化和效率提升。
摘要由CSDN通过智能技术生成

在这里插入图片描述
把2D矩阵平移k步,每移一步各元素都向右平移一位,
边界元素这样处理:
右边界的移到下一行的开头,
右下角的元素移到左上角。

思路:
首先,移了m*n步会回到初始状态,相当于没有平移,
比如example1的矩阵,平移9次,又回到了原来,
所以实际需要平移的次数为k % (m * n)。

我们可以根据(i, j)计算它平移之后的位置,
idx = i * n + j + k, (按行数第几个)
row = idx / n,
col = idx % n
(row, col)是平移之后的矩阵元素位置,它可能不是从(0, 0)开始的,但是保存的时候是要从(0, 0)开始保存的。

这相当于知道了平移之后的位置(row, col),要倒推它对应的平移之前的元素(i, j), 所以只需要把idx - k即可
这里的idx = row * n + col,
-k是向左平移,把它统一成向右平移的计算,于是
idx = row *n + col + (m * n - k),
用这个idx找到平移前的元素grid[ i ][ j ],保存进结果的list即可。

因为是二维矩阵下标找元素,所以比较慢。

//9ms
    public List<List<Integer>> shiftGrid(int[][] grid, int k) {
        int m = grid.length;
        int n = grid[0].length;
        List<List<Integer>> res = new ArrayList<>();
        int nums = m * n;
        
        k = k % nums;
        
        for(int i = 0; i < m; i++) {
            List<Integer> list = new ArrayList<>();
            for(int j = 0; j < n; j++) {
                int idx = (i * n + j + nums - k) % nums;
                list.add(grid[idx / n][idx % n]);
            }
            res.add(list);
        }
        
        return res;        
    }

找到一个方法,是一维下标检索,只要2ms,很快,
它是根据k直接找到位于(0, 0)的初始位置,从这个位置往下走。
不过没有上面那种方法好理解。

    public List<List<Integer>> shiftGrid(int[][] grid, int k) {
        int rowCount = grid.length;                         // Number of rows in grid.
        int colCount = grid[0].length;                      // Number of columns in grid.
        int gridCount = rowCount * colCount;                // Number of cells (i.e. values) in grid.
        k = k % gridCount;                                  // Limit k to max number of cells in grid.  Avoid negatives in next lines.
        int kCol = (gridCount - k) % colCount;              // Column to start copying from.
        int kRow = ((gridCount - k) % gridCount) / colCount;// Row to start copying from.
        int[] innRow = grid[kRow];                          // Array for the row to start copying from.
        int[][] result = new int[rowCount][colCount];       // Create result matrix, to hold shifted values.
        for (int r = 0; r < rowCount; r++) {                // Loop through "to" rows.
            int[] outRow = result[r];                       // Get row array to copy into, so only faster 1D reference in inner loop.
            for (int c = 0; c < colCount; c++) {            // Loop through "to" columns.
                outRow[c] = innRow[kCol];                   // Copy value from grid to result, shifting by copying.
                if (++kCol >= colCount) {                   // Next "from" column.  If at end of row...
                    kCol = 0;                               // Then start "from" columns at first column.
                    if (++kRow >= rowCount)                 // When starting new column, next "from" row.  If at end of grid...
                        kRow = 0;                           // Then start "from" rows at first row.
                    innRow = grid[kRow];                    // Get row array to copy from, so only faster 1D reference when copying.
                }
            }
        }
        return (List)Arrays.asList(result);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值