当前位置:网站首页>2022.07.20_Daily Question
2022.07.20_Daily Question
2022-07-31 07:40:00 【No. い】
1260. 二维网格迁移
题目描述
给你一个 m
行 n
列的二维网格 grid
和一个整数 k
.你需要将 grid
迁移 k
次.
每次「迁移」操作将会引发下述活动:
- 位于
grid[i][j]
的元素将会移动到grid[i][j + 1]
. - 位于
grid[i][n - 1]
的元素将会移动到grid[i + 1][0]
. - 位于
grid[m - 1][n - 1]
的元素将会移动到grid[0][0]
.
请你返回 k
次迁移操作后最终得到的 二维网格.
示例 1:
输入:grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 1
输出:[[9,1,2],[3,4,5],[6,7,8]]
示例 2:
输入:grid
= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
输出:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
示例 3:
输入:grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 9
输出:[[1,2,3],[4,5,6],[7,8,9]]
提示:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
- 数组
- 矩阵
- 模拟
coding
1. 新建数组,直接平移,then store the result
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
List<List<Integer>> res = new ArrayList<>();
int row = grid.length;
int col = grid[0].length;
// Used to store moved data
Integer[][] arr = new Integer[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
// 原本 i, j The number at the position changes the array position after the move
// 行 i => (i + (j + k) / col) % row
// 列 j => (j + k) % col
//【PS】: If you line it, you should pay attention to whether to wrap the line
arr[(i + (j + k) / col) % row][(j + k) % col] = grid[i][j];
}
}
// for (Integer[] rows : arr) {
// res.add(Arrays.asList(rows));
// }
Arrays.stream(arr).forEach(i -> res.add(Arrays.asList(i)));
return res;
}
}
2. 二维数组转为一维数组,存入结果集
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
List<List<Integer>> res = new ArrayList<>();
int row = grid.length;
int col = grid[0].length;
int len = row * col;
int[] arr = new int[len];
int index = 0;
// 2D transformed into 1D after moving
for (int[] rows : grid) {
for (int num : rows) {
arr[((index ++) + k) % len] = num;
}
}
index = 0;
for (int i = 0; i < row; i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < col; j++) {
list.add(arr[index++]);
}
res.add(list);
}
return res;
}
}
边栏推荐
猜你喜欢
随机推荐
简单谈谈Feign
04-SDRAM: Read Operation (Burst)
How to set the computer password?How to add "safety lock" to your computer
Analysis of the principle and implementation of waterfall flow layout
360 push-360 push tool-360 batch push tool
【Star项目】小帽飞机大战(八)
毫米波技术基础
DAY18: XSS vulnerability
Chapter 16: Constructing the Magic Square for Prime Numbers of Order n(5,7)
tidyverse笔记——tidyr包
SCI写作指南
opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
项目 - 如何根据最近30天、最近14天、最近7天、最近24小时、自定义时间范围查询MySQL中的数据?
03-SDRAM: Write operation (burst)
从 Google 离职,前Go 语言负责人跳槽小公司
我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件
熟悉而陌生的新朋友——IAsyncDisposable
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
How to choose a suitable UI component library in uni-app
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】