当前位置:网站首页>【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)
边栏推荐
- [rust notes] 17 concurrent (Part 2)
- One question per day 1765 The highest point in the map
- Leetcode-556: the next larger element III
- 927. Trisection simulation
- 884. Uncommon words in two sentences
- Multi screen computer screenshots will cut off multiple screens, not only the current screen
- 1.13 - RISC/CISC
- Introduction and experience of wazuh open source host security solution
- 做 SQL 性能优化真是让人干瞪眼
- 实时时钟 (RTC)
猜你喜欢
Network security skills competition in Secondary Vocational Schools -- a tutorial article on middleware penetration testing in Guangxi regional competition
Groupbykey() and reducebykey() and combinebykey() in spark
Leetcode-6110: number of incremental paths in the grid graph
Appium foundation - use the first demo of appium
leetcode-6111:螺旋矩阵 IV
LVS简介【暂未完成(半成品)】
传统数据库逐渐“难适应”,云原生数据库脱颖而出
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
Individual game 12
Dynamic planning solution ideas and summary (30000 words)
随机推荐
[rust notes] 16 input and output (Part 1)
Flutter Web 硬件键盘监听
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
js快速将json数据转换为url参数
Introduction et expérience de wazuh open source host Security Solution
【Rust 笔记】17-并发(下)
Bit mask of bit operation
Data visualization chart summary (I)
1039 Course List for Student
【Rust 笔记】15-字符串与文本(下)
Time of process
1996. number of weak characters in the game
Matrixdb V4.5.0 was launched with a new mars2 storage engine!
The difference between CPU core and logical processor
[practical skills] how to do a good job in technical training?
多屏电脑截屏会把多屏连着截下来,而不是只截当前屏
Leetcode-6109: number of people who know secrets
Control unit
做 SQL 性能优化真是让人干瞪眼
对for(var i = 0;i < 5;i++) {setTimeout(() => console.log(i),1000)}的深入分析