一、Problem:
Given a 2D grid of size n * m and an integer k. You need to shift the grid k times.
In one shift operation:
- Element at
grid[i][j]becomes atgrid[i][j + 1]. - Element at
grid[i][m - 1]becomes atgrid[i + 1][0]. - Element at
grid[n - 1][m - 1]becomes atgrid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
1 <= grid.length <= 501 <= grid[i].length <= 50-1000 <= grid[i][j] <= 10000 <= k <= 100
二、Solution:
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
int m = grid.length;
int n = grid[0].length;
int[][] result = new int[m][n];
int t = k % (m * n);
// x is rowth, y is columnth
int x = t / n;
int y = t % n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// 下行找到 grid[0][0]即第一个元素的位置,之后顺序赋值即可
result[x][y] = grid[i][j];
y = y + 1;
if (y == n) {
y = 0;
x = (x + 1) % m;
}
}
}
// change Two-dimensional array to list of list
List<List<Integer>> results = new ArrayList<>();
for (int i = 0; i < m; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = 0; j < n; j++) {
temp.add(result[i][j]);
}
results.add(temp);
}
return results;
}
}
三、解题报告:
本题中有两个注意点,第一个是找到元素所在位置(x 行,y列);第二个是将二维数组变为 list of list。
1、int t = k % (m * n)
该行代码以防 k 大于 二维数组的个数,所以取余,其中 m 是行数,n 是列数;
int x = t / n; // x 是元素所在行数,从 0 开始
int x = t % n; // y 是元素所在列数,从 0 开始
2、将二维数组变为 list of list
使用代码中两层 for 循环赋值即可。