首页 技术 正文
技术 2022年11月9日
0 收藏 781 点赞 2,704 浏览 1677 个字

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:

  1. The height and width of the given matrix is in range [1, 100].
  2. 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里面

 public class Solution
{
public int[][] matrixReshape(int[][] nums, int r, int c)
{
// check if new array is possible.
if(nums.length * nums[0].length != r * c)
return nums; int[][] res = new int[r][c]; int col=0;
int row=0;
for(int i=0; i<nums.length; i++)
{
for(int j=0; j<nums[i].length; j++)
{
if(col == c)
{
col = 0;
row++;
}
res[row][col] = nums[i][j];
col++;
} } return res;
}
}

参考资料:N/A

LeetCode 算法题目列表 – LeetCode Algorithms Questions List

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298