1260. Shift 2D Grid
解题思路
本题要求我们移动二维数组,有两种方法可以简单实现:
- 构建一个新的数组,把旧数组的元素位置根据 k 重新计算之后放到新数组中
- 把数组摊平之后平移,之后再重新构建成二维数组
C++
// 第一种方法
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int col = grid.size();
int row = grid[0].size();
vector<vector<int>> res(col, vector<int>(row, 0));
for (int i = 0; i < col * row; i++) {
// 旧数组元素的列
int ori_col = i / row;
// 旧数组元素的行
int ori_row = i % row;
// 新数组的该元素的列
int new_col = (ori_col + (ori_row + k) / row) % col;
// 新数组该元素的行
int new_row = (ori_row + k) % row;
res[new_col][new_row] = grid[ori_col][ori_row];
}
return res;
}
};
Javascript
/**
* @desc 第二种方法
* @param {number[][]} grid
* @param {number} k
* @return {number[][]}
*/
var shiftGrid = function(grid, k) {
const row = grid[0].length;
// 摊平数组
const arr = grid.flat();
// 减少计算量,且保证 splice 可以正常运作
k = k % arr.length;
// 把后 k 个元素移到前面
arr.unshift(...arr.splice(arr.length-k, k));
const res = [];
while(arr.length) {
// 数组升维
res.push(arr.splice(0,row));
}
return res;
};