把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);
}