当前位置:网站首页>【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)
边栏推荐
- 【云原生】微服务之Feign自定义配置的记录
- Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
- 【Rust 笔记】13-迭代器(下)
- The sum of the unique elements of the daily question
- Is it impossible for lamda to wake up?
- Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
- 1.14 - 流水线
- Introduction to LVS [unfinished (semi-finished products)]
- Leetcode-3: Longest substring without repeated characters
- In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
猜你喜欢
Overview of variable resistors - structure, operation and different applications
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
LeetCode 0108. Convert an ordered array into a binary search tree - the median of the array is the root, and the left and right of the median are the left and right subtrees respectively
redis发布订阅命令行实现
liunx启动redis
1.15 - input and output system
RGB LED infinite mirror controlled by Arduino
Spark中groupByKey() 和 reduceByKey() 和combineByKey()
The connection and solution between the shortest Hamilton path and the traveling salesman problem
QQ computer version cancels escape character input expression
随机推荐
[rust notes] 14 set (Part 1)
Doing SQL performance optimization is really eye-catching
LeetCode 1200.最小绝对差
Collection: programming related websites and books
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
[rust notes] 16 input and output (Part 1)
js快速将json数据转换为url参数
Convolution neural network -- convolution layer
传统数据库逐渐“难适应”,云原生数据库脱颖而出
Introduction to LVS [unfinished (semi-finished products)]
做 SQL 性能优化真是让人干瞪眼
Daily question 2006 Number of pairs whose absolute value of difference is k
Full Permutation Code (recursive writing)
RGB LED infinite mirror controlled by Arduino
Appium automation test foundation - Summary of appium test environment construction
1.14 - assembly line
Open source storage is so popular, why do we insist on self-development?
实时时钟 (RTC)
leetcode-6110:网格图中递增路径的数目
Appium自动化测试基础 — Appium测试环境搭建总结