当前位置:网站首页>【LeetCode】Day94-重塑矩阵
【LeetCode】Day94-重塑矩阵
2022-07-05 06:13:00 【倒过来是圈圈】
题目
题解
二维数组的一维表示
题目需要我们做的事情相当于:
- 将二维数组 nums 映射成一个一维数组;
- 将这个一维数组映射回 r 行 c 列的二维数组。
具体原理是:对于 x∈[0,mn),第 x 个元素在 nums 中对应的下标为 (x / n,x % n),而在新的重塑矩阵中对应的下标为 (x / c,x % c)。所以我们在代码中做对应映射即可。
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m=mat.length,n=mat[0].length;
if(m*n!=r*c)
return mat;
int[][] newMat=new int[r][c];
for(int num=0;num<m*n;num++){
newMat[num/c][num%c]=mat[num/n][num%n];
}
return newMat;
}
}
时间复杂度: O ( r c ) O(rc) O(rc)
空间复杂度: O ( 1 ) O(1) O(1)
边栏推荐
- 传统数据库逐渐“难适应”,云原生数据库脱颖而出
- Navicat连接Oracle数据库报错ORA-28547或ORA-03135
- 快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
- 数据可视化图表总结(一)
- Groupbykey() and reducebykey() and combinebykey() in spark
- Doing SQL performance optimization is really eye-catching
- 剑指 Offer II 058:日程表
- 1041 Be Unique
- On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
- One question per day 1765 The highest point in the map
猜你喜欢
Doing SQL performance optimization is really eye-catching
RGB LED infinite mirror controlled by Arduino
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
WordPress switches the page, and the domain name changes back to the IP address
R language [import and export of dataset]
Real time clock (RTC)
Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
做 SQL 性能优化真是让人干瞪眼
Scope of inline symbol
随机推荐
LeetCode 0107. Sequence traversal of binary tree II - another method
API related to TCP connection
leetcode-556:下一个更大元素 III
[practical skills] technical management of managers with non-technical background
做 SQL 性能优化真是让人干瞪眼
1.15 - input and output system
传统数据库逐渐“难适应”,云原生数据库脱颖而出
实时时钟 (RTC)
Introduction to convolutional neural network
数据可视化图表总结(二)
Overview of variable resistors - structure, operation and different applications
【Rust 笔记】16-输入与输出(下)
剑指 Offer II 058:日程表
On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
Sword finger offer II 058: schedule
Collection: programming related websites and books
SPI details
WordPress switches the page, and the domain name changes back to the IP address
Leetcode-6110: number of incremental paths in the grid graph