当前位置:网站首页>LeetCode 1260 二维网格迁移[数组] HERODING的LeetCode之路
LeetCode 1260 二维网格迁移[数组] HERODING的LeetCode之路
2022-07-20 22:23:00 【HERODING23】
解题思路:
本质上就是数组出列入列的过程,也就是说每个数在原先位置上往后挪动了k个位置,那么就要考虑到行和列的关系,代码如下:
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> ans(m, vector<int>(n));
int row, col;
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
row = (i + (k + j) / n) % m;
col = (j + k % n) % n;
ans[row][col] = grid[i][j];
}
}
return ans;
}
};
但是这种处理还是稍显麻烦,尤其是行和列,需要考虑到是否越两个界限的情况,而另一种方法将数组位置化为一维数组,再往后移动然后复原,更为简便,代码如下:
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> ans(m, vector<int>(n));
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
int index = (n * i + j + k) % (m * n);
ans[index / n][index % n] = grid[i][j];
}
}
return ans;
}
};
边栏推荐
- LNMP------PHP7安装
- [guaranteed research] - sort out and share the problems existing in the previous school reexamination interview
- leetcode 15. 三数之和
- cannot convert parameter 1 from 'class A' to 'class A'
- 【保研】-- 整理分享一下之前学校复试面试存在的问题
- Jz25 merge two sorted linked lists
- Envoy负载均衡与限流设计
- Parsing ansible configuration management file
- 使用MySQL,请用好 JSON 这张牌
- 盛邦安全冲刺科创板:奇安信是其第一大客户(5587 万);其三年收入 4.6 亿、净利润 9504 万,研发投入 7846 万
猜你喜欢
九、ELK安装ElastAlert 2插件钉钉机器人告警
[Baoyan] - interview precautions on the middle line of Baoyan summer camp
让我们用ArcGIS制作一张好看的中国月度气温图
【保研】-- 保研夏令营中开放性问题回答
[guaranteed research] - sort out and share the problems existing in the previous school reexamination interview
有哪些高质量的自学网站?
39 year old layoff + mortgage (no way to live)
Summary of APP page seconds open optimization~
9、 Elk installs elastalert 2 plug-in nailing robot alarm
【FLink】Flink 任务 如何优雅的停止
随机推荐
《强化学习周刊》第54期:i-Sim2Real、GriddlyJS & 逆强化学习(IRL)最新应用
exness:美指三连阴,欧元反弹消化加息预期
cannot convert parameter 1 from 'class A' to 'class A'
Selected papers of "deep neural network machine learning column"
[Flink] how to stop Flink task gracefully
Installing C3d v1.0
俩黑客出狱后 5 天非法获利 200 万:被捕
Go write webassembly
4.76 million. Targeted procurement of Bank of Hebei: F5 load balancing (10 sets)
Measurechildren's understanding
MQ使用场景
[daily news] Google restarts ar glasses plan; Musk's trial with Twitter is scheduled for October this year
Jax calculation Selu function
7.1-wy22 Fibonacci series
Nodejs MD5 salt value
Responsive dream weaving template fan foreign trade website
tried to access field com.mysql.cj.CharsetMapping.COLLATION_INDEX_TO_COLLATION_NAME from class io.de
满街皆是圣贤是可能的
FlinkCDC
Reinforcement learning weekly 54: i-sim2real, griddlyjs & the latest application of inverse reinforcement learning (IRL)