博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
566. Reshape the Matrix
阅读量:4326 次
发布时间:2019-06-06

本文共 2002 字,大约阅读时间需要 6 分钟。

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 = 4Output: [[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 = 4Output: [[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.

题意: 将原矩阵变换成r行c列

思路:将矩阵变为一维数组,然后再变换为r*c矩阵

1     public int[][] matrixReshape(int[][] nums, int r, int c) { 2         int rows = nums.length; 3         if (rows == 0 || r == 0 || c == 0) { 4             return nums; 5         } 6         int cols = nums[0].length; 7  8         if (rows * cols != r * c) { 9             return nums;10         }11 12         int []values = new int[rows*cols];13         int index=0;14         for (int row = 0; row < rows; row++)15             for (int col = 0; col < cols; col++)16             {17                 values[index++] = nums[row][col];18             }19 20         int[][] newNums = new int[r][c];21         index=0;22         for (int i = 0; i < r; i++)23             for (int j = 0; j < c; j++) {24                 newNums[i][j] = values[index++];25             }26         return newNums;27     }

 

转载于:https://www.cnblogs.com/wzj4858/p/7670026.html

你可能感兴趣的文章
用户场景分析
查看>>
MySQL创建数据库及用户
查看>>
Springboot静态页面放在static路径下还是访问不到
查看>>
centos7 重启网卡失败
查看>>
springboot(一)注解
查看>>
07 Mybatis的多表查询1----1对多和多对1
查看>>
debian和ubuntu的sh dash bash
查看>>
java9-8 局部内部类
查看>>
数据库分页
查看>>
Centos6.8源码编译安装PHP7
查看>>
012 debug调试工具的指令
查看>>
慕课网消息的接收与响应3
查看>>
第三十二讲:UML类图(下)
查看>>
linux下更改时区
查看>>
复杂链表的复制
查看>>
code vs 3376 符号三角形
查看>>
[CF193B] Xor(暴力,剪枝,异或)
查看>>
[CF825D] Suitable Replacement (贪心乱搞)
查看>>
大数据笔记(二十五)——Scala函数式编程
查看>>
win7 IIS7 运行vs2003 web 项目 无法识别的配置节“system.webServer” 解决
查看>>