LeetCode 566. Reshape the Matrix (重塑矩阵)
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
题目标签:Array
这道题目给了我们一个matrix 2d array, 让我们根据给的r 和 c 来重新塑造一个新的矩阵。那么首先我们先判断一下,给的r 和 c 能不能用来塑造一个2d array。比较一下总数就可以了。接下来我们就重塑一个2d array 根据给的r 和c,遍历原来的nums, 设两个int,col 和 row, 对于旧的nums 2d array,当我们每次遍历一行里的每一个数字,我们每次col++,意思就是增加列。一旦当我们自己数的col 列 = c 给的列的时候,我们就更新col 列 = 0, 并且row++。 每一次的数字利用自己计数的row 和 col 代入, res[row][col]。
Java Solution:
Runtime beats 38.21%
完成日期:05/10/2017
关键词:Array
关键点:自己来计数row and column, 并存入每一个int到新的2d array里面
1 public class Solution 2 { 3 public int[][] matrixReshape(int[][] nums, int r, int c) 4 { 5 // check if new array is possible. 6 if(nums.length * nums[0].length != r * c) 7 return nums; 8 9 int[][] res = new int[r][c]; 10 11 int col=0; 12 int row=0; 13 for(int i=0; i<nums.length; i++) 14 { 15 for(int j=0; j<nums[i].length; j++) 16 { 17 if(col == c) 18 { 19 col = 0; 20 row++; 21 } 22 res[row][col] = nums[i][j]; 23 col++; 24 } 25 26 } 27 28 return res; 29 } 30 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?